I want to place a music player at the homepage (even maybe every page within same application/domain) and play songs on document load. But the user may open more than one instance of the page that contains this player at the same time.
So, if the user opened the windows w1, w2, w3 with same url, how to let only one window play songs at a time? For example, w1 plays, w2 and w3 do not. And when w1 is closed, w2 and w3 should be able to find this event, then elect for playing songs, and only the winner will be able to play songs.
Update:according the giving hints, I think this should be able to work:
// LOGICAL CODE
// Cookie["playerId"] - record which player instance is running
// Cookie["lastRefreshTime"] - record the running player last update time
// when running player instance is destoried (window is closed), and timeout,
// the left player instances should be able to modify Cookie["playerId"] for running.
function Palyer(){
this.playerId = randomString();
var _this = this;
this.refreshHandle = setInterval(function(){
// non-running players to check whether timeout, then competing
if( Cookie["playerId"] != _this.playerId
&& sysTime - Cookie["lastRefreshTime"] > 1000*2){
// competing for run, may have small probability going wrong
Cookie["playerId"] = _this.palyerId;
}
// running player to update timestamp for avoding timeout
if( Cookie["playerId"] == _this.playerId){
Cookie["lastRefreshTime"] = sysTime;
if (!_this.isInitialized()) {
_this.init();
}
}
}, 1000);
...
}
var player = new Player();