【发布时间】:2016-06-14 18:08:36
【问题描述】:
我正在制作一个 chrome 扩展,在我的后台脚本中我有一个 addListener,但即使它是 onUpdated.addListener,它也会触发不止一次。我添加了一个 if 语句来检查 changeInfo.status == 'complete' 的时间,但它仍然会触发多次。我知道谷歌浏览器有一个与此有关的错误,但那是几年前的事了。有什么解决办法吗?提前致谢。
这是我的 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"
]
}
如果您想知道为什么我的onCreated 中有一个onUpdated,那是因为 onCreated 不是单独工作的,而且我还需要在之前创建的选项卡也更新时触发它(例如,我创建一个选项卡,转到一个 URL,然后使用该选项卡转到另一个 URL)。起初我正在检查changeInfo.status,但当它不起作用时,我将其更改为tab.status,这些不是同一个变量吗?两者似乎都给出了相同的行为(在不应该的时候触发)。
【问题讨论】:
标签: javascript google-chrome google-chrome-extension background tabs