Shazam
Shazam

Reputation: 708

Chrome extensions: is it possible to call a function in the options page from the background page?

How do I call a function in the options page from the background page?

For example, in the options page, you can call:

    chrome.extension.getBackgroundPage().updateIcon("someDifferentIcon.png");

thereby communicating with the background page from the options page. How do you communicate with the options page from the background page?

One possible difficulty is that the options page is not always open (unlike the background), so that may explain why its not built-in (like above). My question is, is it possible to do?

Upvotes: 2

Views: 1267

Answers (2)

legendlee
legendlee

Reputation: 578

A simple approach to implement your idea is using "chrome.extension.sendRequest" API. For example:

options.js:

chrome.extension.sendRequest({id:"updateIcon", filename:"foo.png"});

background.js:

chrome.extension.onRequest.addListener(funciton(request) {
    if (request && (request.id == "updateIcon"))
        updateIcon(chrome.extension.geURL(request.filename));
});

Upvotes: 5

Mihai Parparita
Mihai Parparita

Reputation: 4236

If the options page is already open, you can use chrome.extension.getViews({type:"tab"}) to get a hold of its window object and then call functions on it (you'll need to iterate over the returned views and pick the one with the URL that is the URL of your options page). If it's not open yet, you can use the tabs API to open a tab that points to it first, and then use chrome.extension.getViews.

Upvotes: 1

Related Questions