-2

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.

tlietz
  • 139
  • 1
  • 8
  • Why would that mean that it's called whenever the listener is activated? You said it yourself: the function is called at the point when `addListener()` is called, not when the event occurs. – Barmar Feb 19 '21 at 20:23

2 Answers2

0

onActivated listener fire only once. But it's not because of the event. It's because the JS interpreter when reading your "definition" at this point executes/calls the function only the result is then attached to the listener.

Krilivye
  • 547
  • 4
  • 8
0

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.

Barmar
  • 741,623
  • 53
  • 500
  • 612