google-chrome-extension - 如何动态更改 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"
}
]
}
为什么这行不通?
解决方案
您可以使用后台脚本来实现这一点:
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});
}
});
});
推荐阅读
- javascript - 借助扩展运算符修改对象的属性导致原始对象被修改?
- python - 使用 tf.data 的 One-hot 编码混合了列
- broadleaf-commerce - 在管理员中显示子属性对象列表网格
- javascript - React Native,选择时如何更改TextInputField的BottomborderColor?
- android - Razorpay 错误“合作伙伴凭据需要帐户 ID”
- mysql - ERR_HTTP_HEADERS_SENT]:发送到客户端后无法设置标头
- go - 在 Go 中将时间戳从一种有效的 RFC3339 格式转换为另一种格式
- sql - 将 SQL 数据从备份表复制到其他表
- python - 地址栏显示数据:,同时尝试通过 Selenium 和 Python 使用 ChromeDriver Chrome 进行抓取
- python - 使用正则表达式组更新 python 字典