简体   繁体   中英

How to share data between browser tabs?

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

eg 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.

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
}

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM