我正在製作一個Chrome擴展,在我的後臺腳本中我有一個addListener
,但它不止一次觸發,即使它是一個onUpdated.addListener
。我添加了一條if語句來檢查changeInfo.status == 'complete'
何時,但它仍然是多次發射。我知道Google Chrome有一個與此有關的bug,但那是多年以前的事了。任何解決方案提前致謝。chrome.tabs.onUpdated.addListener不止一次觸發
這裏是我的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
,這些不是同一個變量嗎?兩者似乎都給出了相同的行爲(當他們不應該發射時發射)。
問題,如果我創建一個新的選項卡,然後聽衆會火,因爲'onCreated',但不會一旦新創建的標籤加載完成,它也會觸發'onUpdated'? @mgiuffrida 編輯:沒關係!它就像一個魅力,謝謝你! –