DailyJS

The Local Storage Bridge

Alex R. Young

Subscribe

@dailyjs

Facebook

Google+

libraries modules tabs localStorage client-side

The Local Storage Bridge

Posted by Alex R. Young on .
Featured

libraries modules tabs localStorage client-side

The Local Storage Bridge

Posted by Alex R. Young on .

Doing something as simple as passing values between iframes and tabs is surprisingly awkward, and you'll end up trying anything to get it to work. Krasimir Tsonev has created a library called lsbridge (GitHub: krasimir/lsbridge, License: MIT, npm: lsbridge), or Local Storage Bridge. It allows you to send messages between tabs using Local Storage as a communication channel.

lsbridge

The API uses the .send and .subscribe methods to pass messages one way. You can also call lsbridge.isLSAvailable to check if the Local Storage API itself is available. Here's an example of the usage:

lsbridge.send('my-namespace', { message: 'Hello world!' });

lsbridge.subscribe('my-namespace', function(data) {  
  console.log(data); // prints: { message: 'Hello world!'}
});

console.log(lsbridge.isLSAvailable); // prints "true" or "false"  

Internally, lsbridge uses a setTimeout polling loop to set and remove items. The interval is 100 milliseconds, and there's a separate interval for item removal which is set to a second.

This is a pragmatic way to send data between tabs that doesn't require ugly hacks. For more context behind the library, see Krasimir's blog post Using Local Storage as a communication channel.