admin管理员组文章数量:1394228
In my application I programmed that the system plays an audio to notify the user when he received a notification.
If the user have a lot of browser tabs opened, this audio is played a lot of times (one for tab).
Is there any way to do that the audio only plays once?
Thank you!
In my application I programmed that the system plays an audio to notify the user when he received a notification.
If the user have a lot of browser tabs opened, this audio is played a lot of times (one for tab).
Is there any way to do that the audio only plays once?
Thank you!
Share Improve this question asked Sep 7, 2015 at 8:04 Aral RocaAral Roca 5,9398 gold badges52 silver badges83 bronze badges1 Answer
Reset to default 9You could set a flag in 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);
}
This way, the item tabKey
will be set to the randomKey
of the first tab. Now, when you play the audio, you can do:
if (localStorage.getItem("tabKey") === randomKey) {
playAudio();
}
This will play the audio only in the first tab.
The only problem is, you have to react to the case, that the user is closing the first tab. You can do this by unsetting the tabKey
item on tab close and catching this event in other tabs with the storage
event:
//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 Play audio once in multiple tabsStack Overflow
版权声明:本文标题:Javascript: Play audio once in multiple tabs - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1744748431a2623029.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论