在标签页或网址更改时更改版面扩展名图标



我正在开发一个扩展,我希望图标在活动选项卡或 url 更改时更改。这是我到目前为止所拥有的:

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"]
   }
 ]
}

内容.js

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

弹出窗口.js

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

您正在处理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"]
    }
  ]
}

背景.js

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

最新更新