Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mutex Lock (JS) Shared between multiple tabs of a browser?

Is there any way for two tabs within a browser to share a Mutex (in JavaScript)?

I am working on a web-app using node.js & socket.io, and I want the various tabs to share a single connection with the server. The so-called 'leader' tab is the only one that maintains the connection, while messages to the rest of them are all relayed via this one. Right now, I'm using a leader election algorithm to choose the leader, but given that it takes a second or two to re-elect a new leader if the current one goes down, I wonder if there is a better method to do the same.

like image 545
Kaustubh Karkare Avatar asked Oct 20 '12 09:10

Kaustubh Karkare


People also ask

Are sessions shared between tabs?

Session storage is tab specific and data are not shared between different tabs. Session storage runs in modern browser. sessionStorage.

Can browser tabs communicate?

One of the traditional ways of communicating across Browser Tabs, Popups, and Iframes is Window. postMessage() method. You can send the message as follows. And the target window can listen to the events, as shown below.

Does localStorage work across tabs?

The main features of localStorage are: Shared between all tabs and windows from the same origin. The data does not expire. It remains after the browser restart and even OS reboot.

Does JavaScript need mutex?

Yes, mutexes can be required in Javascript when accessing resources that are shared between tabs/windows, like localStorage. Between the time that the localStorage item is 'got' and 'set', another tab could have modified the value.


2 Answers

There is a module which solves this by using a leader-election over the BroadcastChannel-API. See

like image 91
pubkey Avatar answered Sep 22 '22 23:09

pubkey


There are various libraries that either try to solve the problem of locking directly or provide message passing between tabs, which you could use as a building block. Check out:

  • https://github.com/tejacques/crosstab
  • https://github.com/slimjack/IWC
  • https://github.com/nodeca/tabex
  • http://balpha.de/2012/03/javascript-concurrency-and-locking-the-html5-localstorage/
  • https://github.com/jitbit/TabUtils
like image 34
qbolec Avatar answered Sep 26 '22 23:09

qbolec