Maria
Maria

Reputation: 3525

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

Upvotes: 2

Views: 992

Answers (2)

Alex from Jitbit
Alex from Jitbit

Reputation: 60642

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

Upvotes: 2

cyco130
cyco130

Reputation: 4934

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.

Upvotes: 1

Related Questions