简体   繁体   中英

How To Immediately Change Chrome Extension Icon?

I've seen plugins like Adblocks which can switch plugin icon to grayscale almost with immediate tab change action.

How do I achieve this? Currently I'm doing it with detecting specific URL with content.js and then sending a message to background.js to change the icon. But this is slow and happens after 2-3 seconds after page load.

How do I do this? I've a specific list of URL wildcards on which icon has to be changed.

The chrome.pageAction and chrome.browserAction APIs allow extensions to specify tab-specific state (button tooltip, icon, popup, etc.).

You can use the chrome.webNavigation APIs to detect navigations, or the chrome.tabs API to detect tab state changes. Bind an event listener to either API and update the badge state in the callback:

chrome.webNavigation.onCommitted.addListener(function(details) {
    chrome.browserAction.setBadgeText({
        text: 'whatever',
        tabId: details.tabId  // Important for tab-specific state!
    });
});

(read the documentation to see what's available in the details object.)

Your content script runs, by default, at "document_idle" , meaning "some time after the document is fully loaded and JS engine is idle"

If your "detector script" does not need access to DOM to decide on the icon, you can set it to run at "document_start" , before DOM is loaded:

"content_scripts": [
  {
    "matches": ["*://*.example.com/*"],
    "js": ["detect_url.js"],
    "run_at": "document_start"
  }
],

See Content Script docs for more details.

Alternatively, if you have "tabs" permission, you can listen to relevant tabs events ( onCreated , onUpdated , onReplaced ).

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