我正在制作一个chrome扩展,在我的后台脚本中我有一个addListener
,但是它不止一次触发,尽管它是一个onUpdated.addListener
。我添加了一个if语句来检查何时changeInfo.status == 'complete'
,但它仍然多次触发。我知道Google Chrome有一个与此相关的bug,但那是几年前的事了。有什么解决办法吗?提前谢谢。
这是我的background.js:
// Get the behavior of the plugin; the default is set to "onClick", the other option is "alwaysOn"
chrome.storage.sync.get({
extensionBehavior: 'onClick'
}, function(items) {
if(items.extensionBehavior == 'onClick'){
chrome.browserAction.onClicked.addListener(function() {
// When the extension icon is clicked, send a message to the content script
chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
chrome.tabs.sendMessage(tabs[0].id, {"message": tabs[0].url}, function(response){});
});
});
}
else {
chrome.browserAction.setBadgeText({text:"auto"});
chrome.tabs.onCreated.addListener(function (tab) {
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
if (tab.status == 'complete') {
chrome.tabs.sendMessage(tabId, {"message": tab.url}, function(response){});
}
});
});
}
});
这是我的manifest.json:
{
"manifest_version": 2,
"name": "My Extension",
"version": "1.2.1",
"description": *redacted for privacy reasons*,
"content_scripts": [{
"matches": [
"<all_urls>"
],
"js": ["content_script.js", "jquery-2.2.4.js"]
}
],
"background": {
"scripts": ["background.js"]
},
"options_ui": {
"page": "options.html"
},
"browser_action": {
"default_icon": "blue-logo.png"
},
"permissions": [
"storage",
"activeTab",
"tabs"
]
}
如果您想知道为什么我在我的onUpdated
中有一个onCreated
,这是因为onCreated并不是单独工作的,当以前创建的选项卡也被更新时,也需要它来触发它(就像我创建了一个选项卡,转到一个URL,然后转到另一个带有该选项卡的URL )。一开始我检查的是changeInfo.status
,但当它不起作用时,我将它改为了tab.status
,这不是同一个变量吗?两人似乎都有相同的行为(当他们不应该开枪的时候)。
发布于 2016-06-14 19:04:56
每次创建选项卡时,都要向chrome.tabs.onUpdated
添加一个新的侦听器:
chrome.tabs.onCreated.addListener(function (tab) {
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
...
这意味着,如果您创建了三个选项卡,那么每次更新一个选项卡时,都会调用您的unUpdated
侦听器三次。tab
事件的onCreated
参数也将被忽略,因为onUpdated
回调使用的参数同名。
如果您需要侦听这两个事件,则应分别添加每个侦听器:
chrome.tabs.onCreated.addListener(function (tab) {
...
});
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) {
...
});
https://stackoverflow.com/questions/37819209
复制相似问题