Comparison of data transfer methods between browser tabs in SPA context

Intro

State management on the application level is the task for libraries such as Redux. However, there are situations when the application needs to synchronize a part of the state between instances of the application opened in different tabs of the same browser. As an example, it could be a user authorization state or a shopping cart in an online store. In this case, we need to be able to transfer the state between tabs of the same SPA.

Overview of data transmission methods and definition of criteria for their comparison

Generally, these methods can be divided into two groups: using a server or without it. Let’s briefly describe the pros and cons of the first group:

  • It is possible to synchronize the state not only between tabs of the same browser but also between different devices.
  • Delays in data transfer
  • How convenient is it to use this method?
  • How to get access to all tabs?
  • What format is used for data transfer?
The gif shows two tabs with an opened sample application that contains two buttons — “change state” and “unsubscribe”. When you click “change state” in any of the tabs, both tabs will change the background color, while when you click “unsubscribe”, the tab will stop receiving status updates from the other tabs.

Method 1 — Service worker

To create a communication channel through the Service worker, you need to create a file with the service worker code and register it in the code of your application:

Method 2 — Localstorage

To create a communication channel, we should subscribe to the storage event inside the component:

Method 3 — Broadcast channel

To create a communication channel, we must subscribe to the channel by name inside the component, and the API will independently determine whether to create a new channel or connect to an existing one.

Conclusions

For a real project that needs support for as many browsers as possible, it’s good to choose Service Workers, because:

  • The state is passed to all tabs and/or windows (including the one from which it was sent)
  • Objects are passed instead of JSON strings.

High-level software engineers for powerful web solutions https://intspirit.com/