shanomurphy shanomurphy - 1 month ago 15
Javascript Question

Keep Chrome Extension running on page reload

I'm trying to build a simple chrome extension that inserts/hides a div when the browser action (extension icon) is toggled. I've got the basics working but I would like the extension to remain in it's 'on-state' (i.e div inserted) when the page reloads. It should only be removed when toggled off.

Currently on each reload everything resets.

Answer

I did eventually figure out that I needed to add a listener for chrome.tabs.onUpdated as @ViewSource's excellent answer also stated. Here's the final working example:

manifest.json

{
    "name": "My Extension",
    "version": "0.0.1",
    "manifest_version": 2,
    "background": {
        "scripts": ["background.js"],
        "persistent": false
    },
    "browser_action": {
        "default_icon": "icons/icon-off.png"
    }
    "permissions": [
        "activeTab",
        "<all_urls>"
    ]
}

background.js

var toggle = false;
var status = 'off';
var the_tab_id = '';

function set_status() {
    toggle = !toggle;
    status = 'off';
    if(toggle) { status = 'on'; }
}

function toggle_extension(tab){
    // Set icon
    chrome.browserAction.setIcon({ path: 'icons/icon-'+status+'.png', tabId:tab.id });
    // Pass variable & execute script
    chrome.tabs.executeScript({ code: 'var extension_status = "'+status+'"' });
    chrome.tabs.executeScript({ file: 'inject.js' });
    // Set the tab id
    the_tab_id = tab.id;
}

function my_listener(tabId, changeInfo, tab) {
    // If updated tab matches this one
    if (changeInfo.status == "complete" && tabId == the_tab_id && status == 'on') {
        toggle_extension(tab);
    }
}

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

chrome.tabs.onUpdated.addListener(my_listener);

inject.js

if( extension_status == 'on' ) {
    // do stuff
}
Comments