在我的应用程序中,我编写了程序,当用户收到通知时,系统播放音频以通知用户。
如果用户打开了许多浏览器选项卡,则此音频会播放很多次(一个用于选项卡)。
有什么办法可以使音频只播放一次?
谢谢!
您可以在中设置标记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);
}
}
});
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句