Skip to content Skip to sidebar Skip to footer

Chrome.extension.getBackgroundPage() Function Example

I'm working on a small Chrome extension that needs to run in the background. However, I understand that that isn't possible when I'm using a popup. After some reading it seems that

Solution 1:

Yes, you need to call function from background in your popup. Here's a simple example which demonstrates how it works.

background.js

function backgroundFunction () {
    return "hello from the background!"
}

popup.js

(function () {
    var otherWindows = chrome.extension.getBackgroundPage();
    console.log(otherWindows.backgroundFunction()); 
})();

When you inspect your popup.js you'll see "hello from the background!" in your console. GetBackgroundPage() simply returns window object for your background page, as you probably know all variables are attached to this window object so in this way you will get access to function defined in background scripts.

There is a sample code demonstrating this in chrome documentation see Idle Simple Example and look at file history.js


Solution 2:

The background page is loaded then you extension is loaded into Chrome.

Consider the popup page just as a normal web-page: here, you need to use chrome.runtime to make requests to the background page.

Usually, I do it using an implicit (temporal) or explicit (permanent) channel. With temporal channel:

popup.js

chrome.runtime.onMessage.addListener(function (answer) { /* your code */ });
chrome.runtime.sendMessage({cmd: "shutdown"});

background.js

chrome.runtime.onMessage.addListener(function (request) {
    if (request.cmd === "shutdown") {
        shutdown();
    }
});   

With permanent channel:

popup.js

var port = chrome.runtime.connect({name: "myChannel"});

port.onMessage.addListener(function (answer) { /* your code */ });
port.postMessage({cmd: "shutdown"});

background.js

chrome.runtime.onConnect.addListener(function (port) {
    port.onMessage.addListener(function (request) {
        if (request.cmd === "shutdown") {
            shutdown();
        }
    }
});

UPD. While this way of content-backgrounf communication is fully functional, the current specs advice using chrome.runtime.getBackgroundPage() to call a function in the background script is the requests shouldn't be asynchronous (thus, less coding is needed and easier to read the code). See the manual and other answers to this post to clarify this matter.


Post a Comment for "Chrome.extension.getBackgroundPage() Function Example"