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

标签 javascript audio local-storage

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

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

有没有办法让音频只播放一次

谢谢!

最佳答案

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

这将只在第一个选项卡中播放音频。

唯一的问题是,您必须对用户关闭第一个选项卡的情况使用react。您可以通过在选项卡关闭时取消设置 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);
        }
    }
});

关于Javascript:在多个选项卡中播放一次音频,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32433819/

相关文章:

javascript - Mac 上的 Google Chrome 本地存储

html - 火狐: "TypeError: localStorage is null"

javascript - 声明对象的 JSON 数组并动态添加项目

javascript - 在 vuejs 中测试 firebase 函数

javascript - 一旦元素在 Material-UI 中可见,就触发 CSS 动画

ios - iOS从视频中删除特定声音

javascript - 如何在 Angular 5 中安全地存储本地存储

带有右插入符的 javascript var 会给出奇怪的结果

javascript - 阻止音频播放然后允许使用 jquery 函数结束

c# - 使用 SharpDx 或 IMSourceReader 从 mp4 文件中读取第二个音轨流