Reputation:
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
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:
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
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