问题
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');
回答1:
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.
回答2:
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
回答3:
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);
}
};
来源:https://stackoverflow.com/questions/14443294/how-to-make-postmessage-applicable-to-all-subdomains