私は、同じアプリケーション/ドメイン内のすべてのページであっても、ホームページに音楽プレーヤーを置き、ドキュメントの読み込み時に曲を再生したいと考えています。しかし、ユーザーは、このプレーヤーを含むページの複数のインスタンスを同時に開くことができます。同じURLの複数のユーザーが開いているウィンドウ間の通信
したがって、ユーザーが同じURLのウィンドウw1、w2、w3を開いた場合、一度に1つのウィンドウで1つのウィンドウのみを再生させる方法はありますか?たとえば、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();
短い回答、できません!長い答えは、最初のウィンドウで新しいウィンドウを開いたときに何らかのコントロールがあり、開かれたウィンドウに何らかのフラグを渡すことができます。ユーザーがランダムに同じページを10回ランダムに開くと決めると、クッキーを設定したり、ページがすでに開かれていることを確認するためにローカルストレージを使用したりすることを除いて、それについてはやってください。しかし、window.unloadなどでその値をもう一度削除する必要があります。 – adeneo