user6101582
user6101582

Reputation:

Send messages between windows on different origins without a reference to the window

Window A is any website. The user runs a bookmarklet in this window which downloads a script from my domain. Window B is on my website and has the same domain as the script. What is the best way to send a message from window A to window B when the user runs the bookmarklet?

I was able to get this working by using window.postMessage to communate to a hidden iframe on my domain which used the localstorage api to forward the message to window B. However, I want to know if a simpler method exists.

Method That Worked: Window A -> postMessage -> Hidden iframe on my domain in window A -> storage apis -> Window B

Is there a way to go directly from window A to window B without a hidden iframe or server side logic?

Upvotes: 1

Views: 609

Answers (2)

chrmod
chrmod

Reputation: 1445

It is browser job to make such communication impossible. There is a high risk of cross site scripting attack if script would be able to pass data between domains without restrictions.

Aside of that browser still allow couple ways such communication can happen:

  • postMessage talking to hidden frames
  • browser web-extension with so called content script can listen to changes on one page and transfer them to other page via chrome.runtime.sendMessage (in Firefox extensions you can manage this probably is far more many ways)
  • alternatively you can try:
    • WebRTC data channel or web sockets to create communication between opened tabs
    • SharedWorkers (which should act as hidden iframe)

Specific technique should be used based on your use case. In some cases usage of backend or cookies may to totally sufficient.

To help myself experiment with postMessage communication I've created little library called Spanan https://github.com/chrmod/spanan . Its usage of Javascript Proxies makes messaging less painful (not it is an experiment not a serious library you should use in production)

Upvotes: 1

skobaljic
skobaljic

Reputation: 9644

If there is no connection between windows, which means domain A is not an iframe of domain B and vice versa (and you do not have control over both), than you have to use server side logic. The hidden iframe you used is one way, the other would be following:

You can call the site B periodically or intentionally using script in Window A as:

var cookieScriptUrl = 'http://www.siteB.com/set_cookie.php?';
function sendData( data ) {
    var image = new Image();
    image.src = cookieScriptUrl + data;
};
sendData('likes=3');

You can send a lot of data, keeping in mind the max is around 2Mb.

Further on, in your PHP script set the cookie(s), than you can read them in Window B.

Upvotes: 0

Related Questions