如何动态更改Chrome扩展程序的图标? [英] How to dynamically change a chrome extension's icon?
本文介绍了如何动态更改Chrome扩展程序的图标?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
如何动态更改Chrome扩展程序图标?我当前扩展名的图标名为icon.png,并且与所有js/清单都在同一目录中,目的是将其更改为我尝试过的icon2.png:
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:
示例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"
}
]
}
为什么这行不通?
推荐答案
您可以使用后台脚本来实现:
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()
示例1:让我展示向您发送消息到后台脚本来从内容脚本触发它的方法:
在内容脚本中,发送消息:
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})
在后台脚本中:
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});
}
});
});
这篇关于如何动态更改Chrome扩展程序的图标?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文