0

I want to have one same page open on multiple browser tabs. When I click on ONE browser tab, I want a JavaScript function to be executed ONCE, just one time! Not that that function is being executed 3 times because that one same page is opened on 3 browser tabs for example.

I have tried:

window.addEventListener("focus", () => {
     console.log(document.hasFocus());
});

This works fine if your cursor is focusing on a web browser and keeps switching between tabs on that browser.

But if you first focus your cursor on something else other than that web browser (e.g. computer desktop or code IDE) and then you click on a NON-ACTIVE browser tab, the above code will be executed two times, one time by the previous active tab and another time by the new active tab you just clicked on.

That is my problem.

How can I execute JavaScript code only one time when I click on a web browser tab? Any solution besides JavaScript code is also welcome e.g. tracking pixels or input field autofocus event, just to name samples. I did not mean that tracking pixels techniques will help. I am not using jQuery. I am using VueJs.

Viral
  • 935
  • 1
  • 9
  • 22
O Connor
  • 4,236
  • 15
  • 50
  • 91
  • Maybe what you're looking for is the `Visibility API` https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API – gugateider Feb 19 '20 at 09:39
  • Page Visibility API is acceptable in some use cases but if you have two seperate browser windows visible side-by-side, each window has two tabs. That means there are 4 tabs in total and of source two tabs are visible, each on each window. As human, only one tab can be active. The one you click on. But for Page Visibility API, two tabs are active, each tab on each brower window shown side-by-side. It does not matter on which visible tab you click on. – O Connor Feb 19 '20 at 14:23

1 Answers1

0

You might want to use this ancient method and JS syntax, before you adopt it for your final coding style. Have some classic vanilla flavor. It never hurts.

document.body.onfocus = function(e){console.info(e.type)}
should work exactly as requested...
but since this behavior is somewhat tied to the BOM, some browser vendors (with idiosyncratic behaviors) might require some sort of enforced filtering,  Opera comes to mind. 

But it should be rock solid on all modern browsers including a bonus backward compatibility, as back as Windows 98 browser version. And\or the ancient and now probably forgoten NN 4.7. ( except for the console info event log, but that's not needed for the actual use anyway )
Bekim Bacaj
  • 5,707
  • 2
  • 24
  • 26