简体   繁体   中英

javascript: run code once among all tabs

Everytime a page receives a websocket event, it will play a notification sound. The problem is if user has 10 of these tabs open, all 10 tabs will play the sound.

So is there anyway to run this code only once, among all tabs, without modifying server-side code?

socket.on('notification', function(){
  playSound(); // this will run on every tab, which is annoying
});

This answer to a question about communication between tabs might be a good start.

Once you have a solid way of communication between tabs, you can designate one tab as the "leader" and play the sound only in that one. If the leader dies, the remaining ones can negotiate to elect a new leader. For example, you can give each tab a long random id and the one with the lowest id can become the new "leader" and assume the responsibility to play the sound.

I've spent a fair amount of time developing a library that handles this, it's very small and you can lock like this:

//locked "critical section" code - runs only once
TabUtils.CallOnce("lockname", function () {
    alert("I run only once in multiple tabs");
});

https://github.com/jitbit/TabUtils

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM