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!
You 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);
}
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With