简体   繁体   中英

Chrome Extension: Change Address bar Button Background color at runtime

Is it possible to change button background color on page load event but so far I did not find any such method at all. If it is not possible then I am happy to use some pre-defined images that loads up after page load.

I have tried the following, without success:

script.js

// chrome.browserAction.setIcon("red.png");
chrome.browserAction.setIcon({path:'red.png'});

manifest.json

{
  "name": "Domain Colors",
  "version": "1.0",
  "manifest_version": 2,
  "content_scripts": [{
      "matches": ["http://*/*"],
      "js": ["script.js"]
  }],
  "permissions": [ "tabs", "http://*/*" ],
  "browser_action": {
    "default_title": "Colry",
    "default_icon": "blue.png"
  }
}

In order to use the browserAction API, a background page is required. If you want to keep your current control flow (update icon via a content script), you need to pass messages . Here's the bare minimum:

// script.js
chrome.extension.sendMessage('');
// background.js
chrome.extension.onMessage.addListener(function(message, sender) {
    chrome.browserAction.setBadgeBackgroundColor({
        color: 'red',
        tabId: sender.tab.id
    });
});

The manifest file needs one additional entry:

"background": {
    "scripts": ["background.js"]
}

You don't need content scripts for the purpose of detecting page loads. A single event listener can be used (in the background page):

chrome.tabs.onUpdated.addListener(function(tabId, changeInfo) {
    if (changeInfo.status === 'loading') {
        chrome.browserAction.setBadgeBackgroundColor({
            color: 'red',
            tabId: tabId
        });
    }
});

Have a close look at the documentation of chrome.browserAction.setBadgeBackgroundColor . There are also lots of examples using the browserAction API , you should be able to get a working extension yourself by looking at these samples.

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