首页 > 解决方案 > 如何动态更改 chrome 扩展的图标?

问题描述

如何动态更改 chrome 扩展图标?我当前扩展的图标名为 icon.png 并且与所有 js / manifest 位于同一目录中,目的是将其更改为 icon2.png 我尝试过:

示例 content.js

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

清单.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"
        }
    ]

}

为什么这行不通?

标签: google-chrome-extension

解决方案


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

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});

        }
    });
});

推荐阅读