Skip to content

Instantly share code, notes, and snippets.

@shubhank-srivastava
Created July 5, 2018 19:04
Show Gist options
  • Save shubhank-srivastava/7653c2eed535b964bcd0cfb028ea0416 to your computer and use it in GitHub Desktop.
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).
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