4

I wish to determine using jquery or javascript that is the user has switched tab standing on the same browser?

I.e. if the user is currently standing on browser say mozilla-firefox tab no.1 , now he has opened another tab say tab no.2 , at that point a popup should appear , with the message "tab changed"

user1083472
  • 149
  • 2
  • 9

3 Answers3

10

I believe you can use the window.onblur event which will fire when the current page loses focus.

window.onblur = function() {
    // Your action here
};

In jQuery, you write it this way

$(window).blur(function() {
    // Your action here
});
Liam Newmarch
  • 3,935
  • 3
  • 32
  • 46
  • This will also trigger when you focus the inspect side bar which can cause strange behaviour. – anonymous-dev Jun 08 '22 at 21:12
  • @anonymous-dev this answer is from over a decade ago, and has been closed for more than half of that time. A better solution is to use the Page Visibility API https://developer.mozilla.org/en-US/docs/Web/API/Page_Visibility_API – Liam Newmarch Jun 21 '22 at 08:47
7

Without jQuery

window.onblur = function () {
    // do some stuff after tab was changed e.g.
    alert('You switched the tab');
}

with jQuery:

$('window').blur(function () {
    // do some stuff after tab was changed e.g.
    alert('You switched the tab');
});

Of course displaying alert is not best thing to do, because it focus current tab again :)

Mateusz W
  • 1,981
  • 1
  • 14
  • 16
4

this might work, but will popup when the user leaves th esite in anyway not just tab changes

window.onunload = popup;

function popup() {
  alert('tab changed');
}
Atom Vayalinkal
  • 2,642
  • 7
  • 29
  • 37