问题
How do I change chrome extension icons dynamically? my current extension's icon is named icon.png and is in the same directory as all of the js / manifest, in a goal to change it to icon2.png i tried:
example 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"
}
]
}
Why won't this work?
回答1:
You can use background script to achieve this:
chrome.browserAction.setIcon({path: '../images/1.png', tabId: info.tabId});
You can call this with some listeners:
chrome.tabs.onActivated.addListener()
chrome.tabs.onUpdated.addListener()
chrome.runtime.onMessage.addListener()
Example 1: Let me show you triggering it from content script by sending a message to background script:
In content script, send the message:
chrome.runtime.sendMessage({icon1: true})
And in background script:
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});
})
}
}
Example 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});
}
});
});
来源:https://stackoverflow.com/questions/55327587/how-to-dynamically-change-a-chrome-extensions-icon