How can two tabs interact inside a browser?

How to prepare a communication channel for communication between multiple open tabs in the same browser without server side support?

+3


source to share


2 answers


Take a look at Window / postMessage .

You can also use Window.localStorage

and register a StorageEvent and react to it from another tab.
Interesting to read here: Using the Web Storage API ;

EXAMPLE using localStorage and StorageEvent

Put this in page1.html



<button>CLICK ME TO CHANGE "A" - "B"</button>
<script>
document.querySelector("button").addEventListener("click", function(){
  localStorage.ab = localStorage.ab ===  "A" ? "B" : "A";
});
</script>

      

and it's in page2.html

<script>
window.addEventListener("storage", function( StorageEvent ){
  console.log( StorageEvent );
  alert(StorageEvent.newValue);
});
</script>

      

+3


source


You can also use Web-Sockets to achieve real-time compilation based on tabs and browsers. Libraries like Socket.io make the whole process very easy.



+1


source







All Articles