简体   繁体   中英

Refreshing an icon change for chrome extension

I'm developing a Google Chrome Extension which changes its icon depending of your IP localization. I face issues with refresh after an extension's icon change.

The icon is actually changing thanks to this command from my background.js file.

chrome.browserAction.setIcon ( { path: 'france.png' } );

Unfortunately, the setIcon command seems to be asynchronous. Icon change actually appears a few seconds after the change in the code. Is there a way to force chrome to refresh icons ?

Many chrome extensions seem to be able to control this but I couldn't find out how they manage this.


Here are more details :

In order to understand more clearly, I removed all my javascript code from different files, except the setIcon line. Here is Manifest line which declares my javascript files.

"background": { "scripts": [ "jquery.min.js", "popup.js", "background.js"] },

popup.js : Now empty background.js : Only these two following lines :

console.log ("I'm background script");
chrome.browserAction.setIcon({path: 'france.png'});

After extension reload with the extensions manager, I click on its icon. Chrome make the static html popup to appear and load background.js file. As a proof of it, the text immediately appears on the console window.

But I have to clic a few more times on the icon extension to see it changed by chrome.

I should do something wrong somewhere, but actually, as I removed everything, I have no clue where this delay could come from.

To instantly update the icon handle all relevant webNavigation events in the background script:

chrome.webNavigation.onCommitted.addListener(updateIcon);
chrome.webNavigation.onHistoryStateUpdated.addListener(updateIcon);
chrome.webNavigation.onBeforeNavigate.addListener(updateIcon);

function updateIcon(details) {
    if (details.frameId != 0) {
        return; // only update the icon for main page, not iframe/frame
    }
    chrome.browserAction.setIcon({
        path: {19: "france-19.png", 38: "france-38.png"},
        tabId: details.tabId
    });
}

Your manifest.json should have webNavigation permission, of course.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM