Last week, I came across a situation while working on a simple AngularJS application. I’d to sync the data between multiple open tabs. As you guess, the easy way to sync data between multiple tabs is through local storage. Ofcourse there are better ways of doing this using websockets; but here I am going to explain the client-side way –– using local storage and real time updating other tabs.
I created a demo app in Plunker. Code is given below
The above shows a simple application that stores data in local storage. This works well when there’s only one tab. Our challenge is to ensure the view is same when the application is opened in multiple tabs as well.
Local storage provides an event called storage on window object. Whenever the localstorage gets updated, all the event listeners attached to storage gets invoked. The first parameter to the handler function is an event object which contains an event.key pointing to the local storage value changed.
$rootScope.$apply(), will trigger a digest cycle from root scope, and all the views will be updated with the new model value.
Try opening the following link in multiple tabs. Update the input text from different tabs, and you can see them updating the other tabs as well.