Created
July 5, 2018 19:04
-
-
Save shubhank-srivastava/7653c2eed535b964bcd0cfb028ea0416 to your computer and use it in GitHub Desktop.
A JS function to detect multiple tabs or new tabs in the browser for the same domain (Works for Chrome/Firefox/UC).
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function preventMultiTab(){ | |
if(window.BroadcastChannel){ | |
var tab_sid = (new Date()).getTime(); | |
sessionStorage.setItem('tab_sid', tab_sid); | |
var channel = new BroadcastChannel('tab-connections'); | |
channel.postMessage('ping:get_back_all_ids'); | |
channel.onmessage = function(e) { | |
var message = e.data.split(':'); | |
if(message[0]=='close'){ | |
if(tab_sid > parseInt(message[1])){ | |
channel = null; | |
console.log('New tab detected.'); | |
} | |
}else if(message[0]=="ping"){ | |
channel.postMessage('close:'+tab_sid); | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment