简体   繁体   中英

How to communicate between two different domains through javascript

I am building an embedded chat control with javascript, ajax, and signalr. Users can add it into their websites by adding a bit of javascript that calls back to our servers and requests the javascript needed to build the chat widget. The chat widget is then embedded on their website, but it can be popped out into a new window. The new window is from our server, no longer on their site.

The Task: When user closes the popup I need to re-show the embedded popup and resume the chat as normal.

The Problem: The popup chat is on a different domain (our site) than the embedded chat (their site).

What I have tried:

1) Give the window opening up the popup a function to reset. OnUnload of the pop-out window call window.opener.reset() <--- window.opener gets accessed denied due to cross domain security issues.

2) When popping up the window, start a loop to check local storage. onUnload of the pop-out window set a variable in the browser localstorage. <---- localstorage did not seem to go through cross domains either. I could not see the change even though the code hit.

3) Same as 2) but using browser cookies instead <--- same situation as 2) it does not go across domains.

What I have to work with:

  • Central server and database.
  • Javascript running on their site.
  • Embedded Chat on their site that can pop up a chat window that runs on our site but continues the same chat session.
  • Chat session can be started either in the embedded chat widget or in the popup and should be able to go back and forth between the two easily.

The best solution probably is to use postMessage.

What you would have to do is the following. Let the user insert this content on his page:

// open your popup chat
var popup = window.open(yourpopup);
popup.postMessage("init",
                  "https://tagetUrl.com");


function receiveMessage(event)
{
  if (event.origin !== "http://YOURDOMAIN.org")
    return;
  // initialize your chat again
}
window.addEventListener("message", receiveMessage, false);

In your PopUp you then would have to do something like this:

source = null;
origin = null;
function receiveMessage(event)
{
  source = event.source;
  origin = event.origin;
}
window.addEventListener("message", receiveMessage, false);

When the PopUp closed ( onUnload ) you can send a message back to the original page:

source.postMessage("closed", origin);

I hope i could help.

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