Javascript:在多个标签中播放一次音频

Ara*_*oca 4 javascript audio local-storage

在我的应用程序中,我编程了系统播放音频以在收到通知时通知用户.

如果用户打开了大量浏览器标签,则会播放此音频很多次(一个用于标签).

有什么办法可以让音频只播放一次吗?

谢谢!

bas*_*kum 6

您可以在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);
}
Run Code Online (Sandbox Code Playgroud)

这样,该项目tabKey将设置为randomKey第一个选项卡的项目.现在,当您播放音频时,您可以:

if (localStorage.getItem("tabKey") === randomKey) {
    playAudio();
}
Run Code Online (Sandbox Code Playgroud)

这将仅在第一个选项卡中播放音频.

唯一的问题是,你必须对案例作出反应,即用户正在关闭第一个标签.您可以通过取消设置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);
        }
    }
});
Run Code Online (Sandbox Code Playgroud)