Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome extension, javascript: Why is this firing twice?

I have a very very simple bit of code in my (test) Chrome extension:

    function test()
    {
    alert("In test!");
    }

   chrome.tabs.onUpdated.addListener(function(tabid, changeinfo, tab) {
    var url = tab.url;
        if (url !== undefined) {

        test();
    }
   });

My question is, why is test() firing twice? And more importantly, how do I make it fire just once?

like image 554
Ryan Avatar asked May 29 '11 14:05

Ryan


4 Answers

Have a look at what the different states are when the event is dispatched. I presume, that it is getting dispatched once when the state is "loading" or when the state is "complete". If that is the case, then your problem would be fixed with:

 function test()
    {
    alert("In test!");
    }

   chrome.tabs.onUpdated.addListener(function(tabid, changeinfo, tab) {
    var url = tab.url;
        if (url !== undefined && changeinfo.status == "complete") {

        test();
    }
   });
like image 197
Niklas Avatar answered Oct 21 '22 10:10

Niklas


I was also confused by this and tried to find the answer. Only after some experimentation did I figure out why I was receiving multiple "complete" update events for what I thought was a single page "update".

If your page has iframes, each will trigger a "complete" event and bubble up to the parent content script. So more complex pages will trigger a slew of onUpdated events if they have iframes.

like image 30
kzahel Avatar answered Oct 21 '22 09:10

kzahel


When you write the following code:

chrome.tabs.onUpdated.addListener(function(tabid, changeinfo, tab) {
    var url = tab.url;
        if (url !== undefined) {

        test();
    }
});

You're calling addListener and telling it to call test() not immediately but rather whenever the tab is updated. Tab update events are broadcast by the Chrome browser itself, which in turn, causes your test() code to run.

like image 2
Rob Sobers Avatar answered Oct 21 '22 09:10

Rob Sobers


I know this is old but anyway... it's happening to me too and maybe this can help someone. Looking into the Tab object that the handler function is receiving, I saw that the favIconUrl property is different in both calls so I guess it has something to do with that although I have no idea about the reason behind this.

I thought it was a bug but after a second thought and some testing I discard the bug theory.

What I know so far is that if two properties are changed, the event is triggered twice with the changeInfo object containing one property each time. In other words if for instance the properties that change are status and favIconUrl, then

changeInfo = {status:"complete"};

and then in the next call

changeInfo = {favIconuUrl : ".... whatever ..."};
like image 2
Juan Menéndez Buitrago Avatar answered Oct 21 '22 09:10

Juan Menéndez Buitrago