JesseBuesking
JesseBuesking

Reputation: 6586

Chrome Extension Dev: Updating javascript variables in background.html

I have a working extension, and now I'm trying to add some options/features!

I have a background page which keeps track of the "state" of each tab (per tab javascript variables that hold options/settings). Now I want to have a popup.html file which will have 1 option, a time slider. I'm not concerned with the slider or any html/css. My issue is that I'm unsure of how to communicate the new setting to the background page.

My background page contains some code like this:

chrome.browserAction.onClicked.addListener(function(tab) {    
    Init(tab);
});

...

function Init(tab)
{
    chrome.tabs.sendRequest(tab.id, 
    {
        'TurnOffTimer': false, 
        'TimerIsOn': TimerIsOn, 
        'Interval': Interval,
        'RefreshRate': RefreshRate
    }, responseCallback);
}

TimerIsOn, Interval, and RefreshRate are javascript variables on the same page.

What I need to know is how, once the slider (which is declared in the popup.html) is set and the user clicks 'ok', the timer value can be sent to background.html to be stored in the appropriate javascript variable, and the extension functionality can be updated. I can create another function called Update which will take this updated value and run, but I need to know how I can call the Update function from popup.html if it's declared in background.html.

Hopefully I'm making sense but if clarification is necessary, feel free to ask.

Upvotes: 0

Views: 1100

Answers (1)

serg
serg

Reputation: 111265

You can directly access background page's window object from popup with chrome.extension.getBackgroundPage(). So to change some var in bg page from popup you can just call:

chrome.extension.getBackgroundPage().Interval = 5;

You would need to change your extension a bit, as once you have popup attached to browser action button, chrome.browserAction.onClicked listener won't be firing anymore. You would need to call Init from popup manually in a similar way:

chrome.extension.getBackgroundPage().Init();

And inside Init() manually get selected tab id, as it won't be passed anymore.

Upvotes: 1

Related Questions