在我的应用程序中,我编写了系统播放音频以在用户收到通知时通知他。
如果用户打开了很多浏览器选项卡,则此音频会播放很多次(一个选项卡)。
有没有办法让音频只播放一次?
谢谢!
最佳答案
你可以在 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/