javascript - js Is there any elegant way to communicate between two tabs that are open at the same time?
黄舟
黄舟 2017-05-16 13:39:46
0
4
706

gave an example:

I opened two pages a and b at the same time. I focused on a and performed some operations to let the js on page a process my operations and send the data to the page b next to it. At this time, page b can receive these data and give feedback without refreshing or going through the server. Similar to when listening to songs on the Baidu Music PC web version, if the Baidu Music Box page and the list page have been opened, when I click the "Play" button of a song on the list page, the music box page next to it can automatically start playing. That music without opening a new page.

I always feel that using cookies or something to do this is a bit useless.

黄舟
黄舟

人生最曼妙的风景,竟是内心的淡定与从容!

reply all(4)
阿神

This is an Alibaba interview question with many methods. Communication can be achieved by using the storage event of localstorage; shadredworker can also solve the problem; and websocket can also be used.

仅有的幸福

If you can control the ab page and even decide the URL: sharedworker / localstorage / sessionstorage can be used

世界只因有你
<ul>
<li><a href="/song-1" target="player">song-1</a></li>
<li><a href="/song-2" target="player">song-2</a></li>
<li><a href="/song-3" target="player">song-3</a></li>
</ul>

The attribute target="framename" means opening the link in the specified frame (page).
Can be achieved:
When you click to add items to the shopping cart, if the shopping cart page is already open, only refresh the page instead of opening a new one Shopping cart page.
When you click to play a song, if the player page is already open, only the page will be refreshed instead of opening a new player page.

世界只因有你

Here’s an idea:
The browser opens two web pages with the same domain name at the same time. Their localStorage是共享的,不仅如此,他们之间的localStorage值改变也是可以监听的。同域的a和b两个页面,a页面发生localStorage.set('abc', 123) and b pages can monitor changes in the following ways:

window.addEventListener("storage", function(e){  
  console.log('key:', e.key); // "abc"
  console.log('oldValue:', e.oldValue); // null
  console.log('newValue:', e.newValue); // 123
});
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template