如何动态更改Chrome扩展程序的图标?

时间:2019-03-24 19:20:36

标签: google-chrome-extension

如何动态更改Chrome扩展程序图标?我当前扩展名的图标名为icon.png,并且与所有js /清单都在同一目录中,目的是将其更改为我尝试过的icon2.png:

示例content.js

console.log("content script is running..") //shows in console
chrome.pageAction.setIcon({tabId: tab.id, path: 'icon2.png'}); //nothing

manifest.json:

{
    "manifest_version": 2,
    "name": "B",
    "version": "0.1",
    "options_page": "options.html",
    "background" : {
        "scripts": ["background.js"]
    },
    "permissions": [
        "storage",
        "tabs"
    ],

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

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

}

为什么这行不通?

1 个答案:

答案 0 :(得分:0)

您可以使用后台脚本来实现:

chrome.browserAction.setIcon({path: '../images/1.png', tabId: info.tabId});

您可以通过一些监听器来调用它:

  

chrome.tabs.onActivated.addListener()

     

chrome.tabs.onUpdated.addListener()

     

chrome.runtime.onMessage.addListener()

示例1:让我展示您向内容脚本发送一条消息,从内容脚本触发它:

在内容脚本中,发送消息:

chrome.runtime.sendMessage({icon1: true})

在后台脚本中:

chrome.runtime.onMessage.addListener(function(msg, sender, sendResponse) 
{
  if(msg.icon1) {
     chrome.tabs.query({active:true, windowType:"normal", currentWindow: true},function(d){
        var tabId = d[0].id;
        chrome.browserAction.setIcon({path: '../icon1.png', tabId: tabId});
    })
  }
}

示例2:

chrome.tabs.onActivated.addListener(function(info){
    chrome.tabs.get(info.tabId, function(change){
        var matching = false; // functionality to determine true/false

        if(matching) {
            chrome.browserAction.setIcon({path: '../icon1.png', tabId: info.tabId});
            return;
        } else {
            chrome.browserAction.setIcon({path: '../icon2.png', tabId: info.tabId});

        }
    });
});