Javascript: Play audio once in multiple tabs - Stack Overflow

In my application I programmed that the system plays an audio to notify the user when he received a not

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

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744748446a4591447.html

相关推荐

  • Javascript: Play audio once in multiple tabs - Stack Overflow

    In my application I programmed that the system plays an audio to notify the user when he received a not

    11小时前
    30

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信