Search code examples
javascriptaudiolocal-storage

Javascript: Play audio once in multiple tabs


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!


Solution

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