19

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');
user559126
  • 191
  • 1
  • 3

3 Answers3

13

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

Community
  • 1
  • 1
smnbbrv
  • 19,108
  • 9
  • 62
  • 100
  • This works nicely and returns the full url of the parent page, just grab the value before there is any navigation within the iframe. – dougwig Sep 08 '17 at 19:11
  • 1
    Until I buy wordpress.com.au (or some other tld that allows this) and I get your delicious messages. – Patrick James McDougle Apr 05 '18 at 21:26
  • @PatrickJamesMcDougle you are right, but this is the case of *be careful with your wishes*. The question is *How to make postMessage applicable to all subdomains*. That's why your comment belongs to the question, not to the answer. Finally, the domains like `wordpress.com.au` are not normally considered as TLD, the `a.wordpress.com.au` will be the TLD in this case – smnbbrv Apr 06 '18 at 02:47
10

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.

Ivan Zuzak
  • 15,222
  • 2
  • 60
  • 53
0

You could just parse and interrogate the src attribute of the iframe to determine if it belongs to the correct domain and set the targetOrigin accordingly.

yourIframe.onload = function() {
  var a = document.createElement('a');
  a.href = yourIframe.src;

  if (a.host.endsWith('yourdomain.com')) {
    var targetOrigin = a.protocol + '//' + a.host;

    yourIframe.contentWindow.postMessage(yourMessage, targetOrigin);
  }
};
Daniel Arant
  • 463
  • 1
  • 4
  • 14