我想在主页上放置一个音乐播放器(甚至可能是同一个应用程序/域中的每个页面),并在文档加载时播放歌曲。但是用户可以同时打开包含该播放器的页面的多个实例。因此,如果用户打开具有相同url的窗口w1,w2,w3,如何让一次只有一个窗口播放歌曲?例如,w1播放,w2和w3不播放。当w1关闭时,w2和w3应该能够找到该事件,然后选择播放歌曲,只有获胜者才能播放歌曲。多个用户打开同一网址的窗口之间的通信
更新:根据给出的提示,我觉得这应该是能正常工作:
// 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();
简短的回答,你不能!很长的回答,如果新的窗口被第一个窗口打开,您可以控制某些窗口,并且可以将某种标志传递给打开的窗口,如果用户决定随机打开同一个页面十次,则没有多少除了可能设置一个cookie或使用本地存储来查看该页面已被打开,但是接下来必须在window.unload等上再次删除该值,并且这一切都变得非常不可靠。 – adeneo 2012-03-31 02:32:10