📜 ⬆️ ⬇️

Communication between windows of one browser by means of cookies

The article will be very short, but describes a good way to exchange data between windows in a single browser.

The method will help us react to an event that occurred in another window. For example, as VK does it - when in one tab we have music, and in another we open a video or turn on another track.


The solution is cross-browser, unfortunately now there is no possibility to check it on the phone / tablet, but I think that everything should work.
')
So, the solution is simple and quite elegant - through a cookie.

I used jQuery and the jquery.cookie plugin, but this can all be implemented with the native tools of js itself without a wrapper.

So, we have a "listener" cookie changes:

var lastState = 0; $(document).ready(function() { cookieTimer(); }); function cookieTimer() { var t = $.cookie('state'); if(t != lastState) { lastState = t; $('#stateLog').append('<div>New state: ' + t + '</div>'); } window.setTimeout(cookieTimer, 500); } 

Once every half a second we check the data in the “state” cookie and, if they have changed, we react to the event, in this case we simply output the data to the screen. And also, we write the current state in the lastState variable.

The second script will change the data:

 <button onclick="$.cookie('state', new Date().getTime());">Set new state</button> 

Install the current timestamp in the cookie state.

Also, we can set something in the state_ <timestamp> cookie, for example, “audio.stop”, where the timestamp is the current timestamp that we installed in the cookie state so that the other windows know how to react to our event.

Demo on jsfiddle: listener (open) and installer (open and press the button, then look in the previous window).

Demo 2 in 1

UPD: I will add that this solution is better to use for devices that do not know about localStorage, so that there is no disagreement and misunderstanding among readers.

Source: https://habr.com/ru/post/167265/


All Articles