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 badges
Add a ment  | 

1 Answer 1

Reset to default 9

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);
        }
    }
});

本文标签: Javascript Play audio once in multiple tabsStack Overflow