Search code examples
javascriptgoogle-chrome-extensionevent-listener

Why does passing a function with parenthesis to 'addListener' cause it to only fire once?


In my chrome extension, I have two event listeners and a function updateTabs:

chrome.tabs.onActivated.addListener(updateTabs());
chrome.tabs.onUpdated.addListener(updateTabs);

function updateTabs() {...}

Why does the onActivated listener fire only once, while the onUpdated listener works as expected?

From what I understand, the parenthesis in updateTabs() means that the function is called at that point. However, wouldn't that mean updateTabs() is still called whenever the onActivated listener is fired? It seems like the event listener is being removed somehow and I do not understand why.


Solution

  • The first call is equivalent to this:

    let temp = updateTabs();
    chrome.tabs.onActivated.addListener(temp);
    

    When written this way, it should be clear that the function is only called once before the listener is added. And when you call addListener, you're not providing a function for it to call when the onActivated event occurs, you're passing whatever updateTabs returned.