Dan Klos
Dan Klos

Reputation: 709

Chrome Extension code (message passing?) executes multiple times

Building my first Chrome Extension (for Gmail), using Chrome's OAuth. When I run the following code, it often executes more than once. The "Hi" message passed from background.js to the content.js logs out multiple times when the page is refreshed, and "HERE" is logged out from the background.js file usually more than once. The behavior doesn't seem to be replicated when I go to gmail from a different page, but rather only when I refresh gmail. I'm guessing this has something to do with the "onUpdated" event listener, but I don't understand why it would execute multiple times.

Note: Interestingly if I close gmail, refresh my background.js file, and then reopen gmail (or refresh it), the code appears to only execute once.

Content.js

chrome.runtime.sendMessage({data: "hello"}, function(response) {
});

chrome.runtime.onMessage.addListener(function(request, sender, sendResponse) {
  console.log(sender.tab ?
              "from a content script:" + sender.tab.url :
              "from the extension");
  if (request.data)
    console.log(request.data)
});

Background.js

 chrome.tabs.onUpdated.addListener( function (tabId, changeInfo, tab) {
          if (changeInfo.status == 'complete') {
            chrome.identity.getAuthToken({ 'interactive': true }, function(token) {
              chromeIdentityToken = token
              chrome.runtime.onMessage.addListener(
                function(request,sender,sendResponse){
                  console.log("HERE")

                  <Program code>

                  chrome.tabs.query({active: true, currentWindow: true}, function(tabs) {
                    chrome.tabs.sendMessage(tabs[0].id, {data: "Hi"}, function(response) {
                    });
                  });
                }
              );
            });
          }
        })

Upvotes: 2

Views: 864

Answers (1)

Brian
Brian

Reputation: 1553

When adding listeners, you need to make sure you only add each once. It appears that you add a listener multiple times, without ever cleaning up the old listeners, which does not overwrite the old listener, it just keeps adding more listeners.

For example:

chrome.runtime.onMessage.addListener(
    function(request,sender,sendResponse){
        console.log("HERE")
    });
chrome.runtime.onMessage.addListener(
    function(request,sender,sendResponse){
        console.log("HERE2")
    });

In this scenario, the second listener does not overwrite the first; you would print both "HERE" and "HERE2".

Upvotes: 1

Related Questions