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

2023-12-26

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

示例内容.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"
        }
    ]

}

为什么这不起作用?


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

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

        }
    });
});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何动态更改 Chrome 扩展程序的图标? 的相关文章

随机推荐