Use a load event listener to give the window time to be ready for you to add your Tab event listeners and create the polling service for the existing tab. Then use an unload event listener to do your cleanup.

Answer from Neil on Stack Overflow
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Mozilla › Add-ons › WebExtensions › API › tabs › onActiveChanged
tabs.onActiveChanged - Mozilla - MDN Web Docs
July 17, 2025 - browser.tabs.onActiveChanged.addListener(listener) browser.tabs.onActiveChanged.removeListener(listener) browser.tabs.onActiveChanged.hasListener(listener) ... Adds a listener to this event. ... Stop listening to this event. The listener argument is the listener to remove. ... Check whether listener is registered for this event. Returns true if it is listening, false otherwise. ... The function called when this event occurs.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Mozilla › Add-ons › WebExtensions › API › tabs › onCreated
tabs.onCreated - Mozilla - MDN Web Docs
July 17, 2025 - browser.tabs.onCreated.addListener(listener) browser.tabs.onCreated.removeListener(listener) browser.tabs.onCreated.hasListener(listener) ... Adds a listener to this event. ... Stop listening to this event. The listener argument is the listener to remove. ... Check whether listener is registered for this event. Returns true if it is listening, false otherwise. ... The function called when this event occurs.
Discussions

Listening to tab open/close and dealing with existing tabs
I'm trying to do something every time a new tab opens up, both via firefox starting and when a new tab is added after firefox starts. I've been following the example at: https://developer.mozilla... More on stackoverflow.com
🌐 stackoverflow.com
Change a tab's DOM from Event Page
Communities for your favorite technologies. Explore all Collectives · Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work More on stackoverflow.com
🌐 stackoverflow.com
Run custom function before open in new tab
I am using an tag instead of a button because I need to add the feature that allow user to right click and then open in new tab: The issue right now is that this tag have an onClick func... More on stackoverflow.com
🌐 stackoverflow.com
Event listener across tabs - javascript
I have two windows: window A and window B. window A and window B are active on the same Web-browser. window A contains a script. Questions: Is it possible for window A to listen to events that... More on stackoverflow.com
🌐 stackoverflow.com
🌐
freeCodeCamp
freecodecamp.org › news › event-handling-in-javascript-with-examples-f6bc1e2fff57
How to handle event handling in JavaScript (examples and all)
May 19, 2018 - The other methods allow it. An event object is passed as an argument (optional) to the handler which contains all the information related to the event (in our case, mousedown) on the window. Open the developer tools (Inspect Element) on this page and copy paste the following code in the console panel and hit enter. window.addEventListener("mousedown",function(event){ alert("window"); console.log(event); }); After that, you can go over to any section of the current tab and right click to see the console and the info related to this event, as shown below in the snapshot.
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › EventTarget › addEventListener
EventTarget: addEventListener() method - Web APIs | MDN
May 22, 2026 - It works on any event target, not just HTML or SVG elements. The method addEventListener() works by adding a function, or an object that implements a handleEvent() function, to the list of event listeners for the specified event type on the EventTarget on which it's called.
Top answer
1 of 3
2

I can't say what's the best solution for the particular use case, but there are various points to consider when deciding what's the best tradeoff:

  • the decision to use an a or button tag should not be determined by the presence of the menu. One is a navigational element and the other is used to perform actions on the page. If it's a navigation on a website, <a> is probably the right tag.
  • the context menu is a browser "thing" and it's in the control sphere of the user. Depending upon your site's philosophy you should not mess up with the browser's basic functionality.
  • when the user navigates away from your page, the browser will trigger the beforeunload event, which will trigger when the current page is being closed. It is a browser's native functionality (the same you get here on StackOverflow when you leave a page with unsaved changes), so it's not customizable in style, but it suits more an HTML-first approach. If you need an 'unsaved changes' message, this is the usual way to go.
  • you can use good ol' window.open with target _blank in a button javascript handler if you want to expose a button with the open in new tab functionality. This way you stay in your JavaScript context and can do whatever you need.
  • if you want more of a Single Page Application style, you can replace the native context menu with something else, as suggested, but you have to evaluate if you are building an application or a website. I like the websites I use to behave like websites and do not interfere with my browser's basic capabilities. YMMV.

Probably there are more considerations worth taking, but this are the ones from the top of my mind.

2 of 3
1

You already correctly figured out that it cannot work the way you want. You need an idea, right? Here is it: therefore, you need to modify your design. This way, you can combine both kinds of behavior you need.

One of the different possible solutions could be this: on your <a> element, you can handle the event "contextmenu". In the handler of this event, you can implement some custom context menu, or some equivalent behavior that gives the user the opportunity to choose one of alternative actions. At the same time, if the user simply activates the anchor, the navigation will load a new page according to a href value, and, if the user holds Shift key — in a new tab.

Let's assume for simplicity that the page has only one <a> element:

<a href="https://stackoverflow.com">Stack overflow</a>

Then it could be set up like this:

const anchor = document.querySelector("a"); // or more complicated selector
anchor.addEventListener("contextmenu", event => {
    // activate menu or something, depending on event.target
});

One of the options in this custom context menu could provide the optional side effect you want. One option may be navigation to the page according to anchor's href, but with the call to your side-effect function.

How to implement a custom menu behavior? This is a separate question. I personally have such a component so I can share it. Or you can implement something, depending on what you want.

Another alternative could be a composite control that has two inner elements: <a>, to provide navigation to the page according to href, in a separate tab or not, and another one to provide the choice of action, not necessarily simulating the behavior of a context menu.

You decide.

🌐
Tom McFarlin
tommcfarlin.com › tab-events-in-bootstrap
Managing Tab Events in Bootstrap 3 | Tom McFarlin
August 26, 2015 - In the markup above, I’ve got a simple unordered list of three tabs the first of which is active as denoted by its classname. This will create a list of navigation options: ... The first of which will be marked as active and the others that will be marked as active when clicked and then will trigger a pane of content to change on the page. Next, I’ll write some JavaScript that will attach an event handler to each of the anchors contained in the above list items that will read the href attribute of the anchor when it has been clicked.
Find elsewhere
🌐
Scriptcase
forum.scriptcase.net › scriptcase 9
Add a "OnClick" javascript event listener on Tabs - Scriptcase 9 - Scriptcase Low-code
September 29, 2020 - Hi. How can I add an “OnClick” event listener to tabs? My tabs are “Blocks” defined in the layout section as “Tabs”. I need to reload the Tab content each time the user clicks on the Tab. I noticed that the SC “OnScriptInit” is triggered only when user clicks on an object within ...
🌐
Eloquent JavaScript
eloquentjavascript.net › 15_event.html
Handling Events :: Eloquent JavaScript
Of course, the program has to remember ... the software to feel unresponsive. This approach is called polling. Most programmers prefer to avoid it. A better mechanism is for the system to actively notify the code when an event occurs. Browsers do this by allowing us to register functions as handlers for specific ...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Mozilla › Add-ons › WebExtensions › API › tabs › onRemoved
tabs.onRemoved - Mozilla - MDN Web Docs
July 17, 2025 - The function called when this event occurs. The function is passed these arguments: ... object. The tab's window ID, and a boolean indicating whether the window is also being closed. See the removeInfo section for more details. ... function handleRemoved(tabId, removeInfo) { console.log(`Tab: ${tabId} is closing`); console.log(`Window ID: ${removeInfo.windowId}`); console.log(`Window is closing: ${removeInfo.isWindowClosing}`); } browser.tabs.onRemoved.addListener(handleRemoved);
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Mozilla › Add-ons › WebExtensions › API › tabs › onActivated
tabs.onActivated - Mozilla - MDN Web Docs
browser.tabs.onActivated.addListener(listener) browser.tabs.onActivated.removeListener(listener) browser.tabs.onActivated.hasListener(listener) ... Adds a listener to this event. ... Stop listening to this event. The listener argument is the listener to remove. ... Check whether listener is registered for this event. Returns true if it is listening, false otherwise. ... The function called when this event occurs.
🌐
Derk-jan
derk-jan.com › articles › 2020 › 05 › cross-tab-events
Cross tab events · Code in Bits and Pieces - Derk-Jan
May 4, 2020 - For our settings, it makes // perfect sense, as they're not sensitive. const [value, setValue] = useState(() => JSON.parse(localStorage.getItem(event) || "null"), ); useEffect(() => { const onStorage = (ev) => { if (ev.key !== event) { return; } setValue(JSON.parse(ev.newValue)); }; // This will trigger on storage events. That usually means that it will // trigger in all browsing contexts that are currently blurred (so not the // current, active/focussed one). This doesn't hold for older browsers. IE10 // for example will send the event to the calling tab as well.
🌐
Medium
medium.com › @manishasiram › handling-browser-events-browser-window-tab-close-browser-close-e66ada5026f1
Handling Browser Events- Browser window / tab close & Browser close | by Manisha Siram | Medium
October 14, 2024 - To handle the browser tab or window close event in Angular, we need to hook into the browser’s beforeunload event. However, browsers…