Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make postMessage applicable to all subdomains

Tags:

In window.postMessage second attribute specifies domain to which my message can be sent. Is there any way to specify that it is applicable to all subdomains.

Things tried:

iframe.contentWindow.postMessage('The message to send.','http://*.wordpress.com');
iframe.contentWindow.postMessage('The message to send.','http://wordpress.com');
like image 287
user559126 Avatar asked Jan 21 '13 16:01

user559126


People also ask

Does postMessage work cross domain?

PostMessage() is a global method that safely enables cross-origin communication. It's a lot like Ajax but with cross-domain capability. We'll give it a whirl by setting up two-way communication between a web page and an iframe whose content resides on another server.

Can a URL have multiple subdomains?

Each domain name can have up to 500 subdomains. You can also add multiple levels of subdomains, such as info.blog.yoursite.com. A subdomain can be up to 255 characters long, but if you have multiple levels in your subdomain, each level can only be 63 characters long.

What is window postMessage () used for?

postMessage() The window. postMessage() method safely enables cross-origin communication between Window objects; e.g., between a page and a pop-up that it spawned, or between a page and an iframe embedded within it.

How do you send iframe to postMessage?

postMessage in your web app sends to the main document's window , not to the iframe's. Specify the iframe's window object: document. getElementById('cross_domain_page').


2 Answers

It is possible without knowing all domains names. Just get a referrer URL and you actually get the origin from that:

var parentOrigin = document.referrer.match(/^.+:\/\/[^\/]+/)[0];

Now, the only thing is to check whether the URL matches the criteria (ends with wordpress.com) and if yes, allow the message to this specific domain.

Works only until the user navigates inside the iframe somewhere else: the referrer is changed. However, the referrer can be saved in an iframe's localStorage so you have a list of possible domains and can send the message to every domain from the list a proposed by Ivan Zuzak

like image 82
smnbbrv Avatar answered Dec 22 '22 04:12

smnbbrv


Nope, not possible.

The only scenario in which you can help yourself is if you know that the target iframe is from a known, finite set of origins (e.g. "http://a.wordpress.com", "http://b.wordpress.com" and "http://c.wordpress.com"). In this case, just make a postMessage request for each of the origins, since only one of those will succeed and the other ones will fail.

like image 42
Ivan Zuzak Avatar answered Dec 22 '22 02:12

Ivan Zuzak