0

If I open a new tab B from page A with window.open or _blank. A and B are in the same origin.

Q1: When I set or clear the sessionStorage on page B, how can I update the sessionStorage of page A synchronously?

Q2: If I use localStorage to share data, how can I clear this data after all tabs are closed?

Eddie
  • 26,593
  • 6
  • 36
  • 58
funlin
  • 1
  • Possible duplicate of [browser sessionStorage. share between tabs?](https://stackoverflow.com/questions/20325763/browser-sessionstorage-share-between-tabs) – Oleg May 20 '19 at 06:48

2 Answers2

0

One easy way can be

Maintain the no of tabs in localStorage and while closing tabs check if it is the last one, if yes then remove the sessionStorage from localStorage

Agam kumar
  • 11
  • 2
0

Q1: Session storage is separated by tabs, so it is not possible to operate on sessionStorage of page B from page A. BUT you can use localStorage as a link to control anything from every tab and window, just cleverly use an event listener attached to the storage.

window.addEventListener('storage', function(e) {  
  console.log(e + ' updated on localStorage');
  // Code to modify sessionStorage here
});

Q2: You need to keep track of how many tabs are open, as this is relatively easy, it can lead to errors (all tabs beign closed at once won't trigger the clear), you need to attach an event listener for the close event.

window.addEventListener('unload', function(e) {  
  console.log(e);
  // Code to clear the storage
});
Jalu
  • 332
  • 3
  • 13