How to Know If Browser Tab Is Already Open Using JavaScript

Determine if the browser already opened an URL

You can write cookie after your page loaded in the first tab, check it on the server side and show the user warning instead of actual page content if this cookie is set and the second tab is opened. To handle the case when a user closes the only opened tab you can remove that cookie in onbeforeunload handler.

how to find particular site is already open or not in the browser?

There is no way to run any client side code in an HTML formatted email. So this is impossible.

The closest you could come would be to:

  1. use some kind of token to identify a user (e.g. stored in a cookie)
  2. run some heart beat code to see if they are still on the page (e.g. use XMLHttpRequest to request a 1 byte file every 15 seconds using a page id generated when the page was loaded and the user id in the cookie)
  3. check on the server to see if a heart beat from a different page was received recently when a new copy of the page is loaded
  4. serve different content if it is

How to tell if browser/tab is active

You would use the focus and blur events of the window:

var interval_id;
$(window).focus(function() {
if (!interval_id)
interval_id = setInterval(hard_work, 1000);
});

$(window).blur(function() {
clearInterval(interval_id);
interval_id = 0;
});

To Answer the Commented Issue of "Double Fire" and stay within jQuery ease of use:

$(window).on("blur focus", function(e) {
var prevType = $(this).data("prevType");

if (prevType != e.type) { // reduce double fire issues
switch (e.type) {
case "blur":
// do work
break;
case "focus":
// do work
break;
}
}

$(this).data("prevType", e.type);
})

Click to view Example Code Showing it working (JSFiddle)



Related Topics



Leave a reply



Submit