targetOrigin 需要 * 或精确的 uri,即没有子域通配符。
如果您想发布到多个目标,则需要为每个目标单独调用postMessage()。为了使这更容易,您可以将所有域放入一个列表并遍历该列表,而不是对每个调用进行硬编码。
var someData = {};
var subdomains = ["one","two","three"];
for(var subdomain of subdomains){
let target = "http://"+subdomain+".example.com"
window.postMessage(someData,target);
}
但这伴随着保持列表更新的维护成本
现在,根据您的代码在哪一端,您还可以使用某些方法在运行时获取准确的 uri。注意示例使用URL 仅解析协议和主机以获取适当的值以传递给 postMessage。
如果你最后打开了一个窗口,或者 iframe 的父级,你可以只获取 src、href 或任何用于指示窗口、iframe 等的 url 的属性。
//if using for instance window.open()
//you already know the url as it has to be passed to the function
var target = window.open("http://example.com/some/path");
//so in this case you would first save the url to a variable and use that variable for both
var url = new URL("http://example.com/some/path");
var targetDomain = url.protocol + "//" + url.host;
var target = window.open(url.href);
target.postMessage("message",targetDomain);
//if using an iframe just grab the src property and parse the domain from that
var url = new URL(iframeElement.src);
var targetDomain = url.protocol+"//"+url.host;
iframeElement.contentWindow.postMessage("message",targetDomain);
现在,如果您在另一边,即在 iframe 或打开的窗口中,您可以使用document.referrer,但从安全页面打开非安全 URL 时除外。意思是当您的页面使用https:// 时打开http:// url 时不会设置document.referrer
var url = new URL( document.referrer );
var target = url.protocol+"//"+url.host;
//opened window
window.opener.postMessage("message",target);
//iframe
window.parent.postMessage("message",target);