Javascript:在多个选项卡中播放一次音频

Javascript: Play audio once in multiple tabs

本文关键字:音频 一次 播放 选项 Javascript      更新时间:2023-09-26

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

如果用户打开了很多浏览器选项卡,这个音频会被播放很多次(一个选项卡)。

是否有办法做到音频只播放一次?

谢谢!

您可以在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);
        }
    }
});