2015-09-07 68 views
3

在我的應用程序中,我編程設定系統播放音頻以在用戶收到通知時通知用戶。Javascript:在多個標籤中播放音頻一次

如果用戶打開了許多瀏覽器選項卡,則會播放該音頻很多次(一個用於製表符)。

有沒有辦法做到音頻只播放一次

謝謝!

回答

4

您可以設置一個標誌localStorage

//create random key variable 
var randomKey = Math.random() * 10000; 
//set key if it does not exist 
if (localStorage.getItem("tabKey") === null) { 
    localStorage.setItem("tabKey", randomKey); 
} 

這樣一來,該項目tabKey將被設置爲第一個選項卡的randomKey。現在,當您播放音頻時,您可以執行以下操作:

if (localStorage.getItem("tabKey") === randomKey) { 
    playAudio(); 
} 

這將僅在第一個選項卡中播放音頻。

唯一的問題是,您必須對此情況做出反應,即用戶正在關閉第一個選項卡。您可以通過取消對標籤關閉tabKey項目,並在其他選項與storage事件捕獲這個事件做到這一點:

//when main tab closes, remove item from localStorage 
window.addEventListener("unload", function() { 
    if (localStorage.getItem("tabKey") === randomKey) { 
     localStorage.removeItem("tabKey"); 
    } 
}); 

//when non-main tabs receive the "close" event, 
//the first one will set the `tabKey` to its `randomKey` 
window.addEventListener("storage", function(evt) { 
    if (evt.key === "tabKey" && evt.newValue === null) { 
     if (localStorage.getItem("tabKey") === null) { 
      localStorage.setItem("tabKey", randomKey); 
     } 
    } 
}); 
+0

驚人!只有一個問題:如何告訴其他選項卡,當第一個選項卡關閉時執行這段代碼?萬分感謝! –

+0

如果用戶關閉第一個選項卡,如何將tabKey再次設置爲空? –

+0

@AralRoca我更新了我的答案,並附上了一個關於如何做的例子。 – basilikum