Created
October 28, 2015 02:20
-
-
Save NaokiStark/48f0c9bd867cf7ec5b0c to your computer and use it in GitHub Desktop.
This file contains hidden or 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
<html> | |
<head> | |
<meta charset="utf-8"> | |
<title></title> | |
</head> | |
<body> | |
<h1>Tab sync</h1> | |
<p>This tab is: <span id="tType"></span></p> | |
<script type="text/javascript"> | |
(function() { | |
window.iAmClosing=false; | |
window.isWindowParent =false; | |
window.onload =function(){ | |
function addEvents(){ | |
window.addEventListener('storage', function (event) { | |
if (event.key == 'wsConnected' && !iAmClosing) { | |
//Variable local, este indica que esta pestaña es padre. | |
window.isWindowParent=true; | |
window.openSocket(window.openCallback); | |
} | |
}); | |
window.onbeforeunload = function (e) { | |
//si es padre | |
iAmClosing=true; | |
if(window.isWindowParent){ | |
localStorage.setItem('wsConnected','false'); | |
} | |
} | |
} | |
//Funcion de ejemplo: | |
window.openSocket = function(callback){ | |
//Si todo sale ok, decimos que está conectado | |
localStorage.setItem('wsConnected','true'); | |
window.isWindowParent=true; | |
if(callback!==undefined){callback();} | |
} | |
//Callback de openSocket | |
window.openCallback=function(){ | |
var span=document.getElementById('tType'); | |
span.innerHTML=(window.isWindowParent)?'Parent':'Children'; | |
} | |
setTimeout(function(){addEvents();},1000); | |
console.log(localStorage.wsConnected!='true') | |
if(localStorage.wsConnected!='true'){ | |
setTimeout(function(){openSocket(window.openCallback);},1000); | |
}else{ | |
window.openCallback(); | |
} | |
}; | |
})(); | |
</script> | |
</body> | |
</html> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment