标签页或网址更改时更改Chrome扩展程序图标

时间:2017-11-11 13:48:16

标签: javascript html google-chrome-extension

我正在处理扩展程序,并希望在活动标签页或网址更改时更改图标。这是我到目前为止所拥有的:

的manifest.json

{
  "manifest_version": 2,

  "name": "Link2QR",
  "description": "chrome_extension",
  "version": "1.0",

  "browser_action": {     
    "default_icon":"icon.png",    
    "default_popup": "popup.html"
   },

  "permissions": [
  "activeTab",
  "https://ajax.googleapis.com/",
  "tabs"
   ],

 "content_scripts": [
  {
    "matches": ["<all_urls>"],
    "js": ["content.js"]
   }
 ]
}

content.js

if(onSupportedPageNeedChangeIcon) {
    chrome.runtime.sendMessage({ "newIconPath" : "testimage.png" });
}

popup.js

chrome.runtime.onMessage.addListener(
   function(request, sender, sendResponse) {
   chrome.browserAction.setIcon({
       path: request.newIconPath,
       tabId: sender.tab.id
   });
});

1 个答案:

答案 0 :(得分:2)

您正在处理popup.js中的消息,我认为该消息正在browser_action弹出页面中运行。

popup.js因此仅在单击扩展按钮时运行。

您应该在background.js中处理它:

的manifest.json

{
  "manifest_version": 2,
  "name": "test",
  "version": "0.0.1",
  "background": {
    "scripts": ["background.js"]
  },
  "browser_action": {
    "default_icon": {
      "24": "icon.png",
      "25": "icon.png"
    }
  },
  "content_scripts": [
    {
      "matches": ["<all_urls>"],
      "js": ["content.js"]
    }
  ]
}

background.js

chrome.runtime.onMessage.addListener(
   function(request, sender, sendResponse) {
   chrome.browserAction.setIcon({
       path: request.newIconPath,
       tabId: sender.tab.id
   });
});