1

我正在製作一個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,這些不是同一個變量嗎?兩者似乎都給出了相同的行爲(當他們不應該發射時發射)。

回答

1

你每次創建一個標籤時添加新的監聽器chrome.tabs.onUpdated

chrome.tabs.onCreated.addListener(function (tab) { 
    chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) { 
     ... 

如果創建三個選項卡,這意味着,你的聽衆unUpdated將調用任何一個時間標籤更新三次。 onCreated事件的參數tab也被忽略,因爲onUpdated回調接受的參數名稱相同。

如果你需要聽這兩個事件,你應該添加單獨的每個聽衆:

chrome.tabs.onCreated.addListener(function (tab) { 
    ... 
}); 
chrome.tabs.onUpdated.addListener(function (tabId, changeInfo, tab) { 
    ... 
}); 
+1

問題,如果我創建一個新的選項卡,然後聽衆會火,因爲'onCreated',但不會一旦新創建的標籤加載完成,它也會觸發'onUpdated'? @mgiuffrida 編輯:沒關係!它就像一個魅力,謝謝你! –