How to share data between browser tabs?

烂漫一生 提交于 2021-02-10 15:56:06

问题


I have to develop a program where I need to get the event from server and want to update the web page.

e.g. I have multiple browser tab opened for chat and each chat page have its own thread to fetch the event from the server but once the one thread among the chat will fetch the event than other get empty stack of event due to extract by the another Chat page.

So, here my concern is to share event with multiple chat pages without refreshing the page.


回答1:


Sound like you could use postMessage to have the tab that gets the message share it with all the other pages on your domain.

postMessage(JSON.stringify({chatmsg: someVarFromServer}), "http://www.mydomain.com");

Have other chat pages listen for message events:

window.addEventListener("message", receiveMessage, false);

function receiveMessage(event) {
    // reject foreign messages!
    if (event.origin !== "http://www.mydomain.com") return;

    var message = JSON.parse(event.data).chatmsg;

    // this other page now has the message
}



回答2:


If you want to develop a real-time chat application written in pure Javascript I highly recommend APE (edit: 2021 seems not maintained anymore) which is a robust start point for such goals.
If you don't want to use a framework here are 2 cross-browser solutions:

  • Check for events by sending an AJAX request periodically
  • Use a third-party application for receiving events such as Flash's XML sockets


来源:https://stackoverflow.com/questions/10885751/how-to-share-data-between-browser-tabs

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!