Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/435.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript window.opener.postMessage与多个子域跨源_Javascript_Cross Domain_Postmessage_Multiple Domains - Fatal编程技术网

Javascript window.opener.postMessage与多个子域跨源

Javascript window.opener.postMessage与多个子域跨源,javascript,cross-domain,postmessage,multiple-domains,Javascript,Cross Domain,Postmessage,Multiple Domains,我尝试在执行以下操作时允许多个子域: window.opener.postMessage(...); 这是可行的,但并不安全,因为所有可能的域都是允许的,我不希望这样: window.opener.postMessage('MyMSG', '*'); 这适用于单个域: window.opener.postMessage('MyMSG', 'https://example.com'); 但是,如果我想允许这样做:**.example.com怎么办 当然,这是: window.opener.p

我尝试在执行以下操作时允许多个子域:

window.opener.postMessage(...);
这是可行的,但并不安全,因为所有可能的域都是允许的,我不希望这样:

window.opener.postMessage('MyMSG', '*');
这适用于单个域:

window.opener.postMessage('MyMSG', 'https://example.com');
但是,如果我想允许这样做:**.example.com怎么办

当然,这是:

window.opener.postMessage('MyMSG', '*.example.com');
window.opener.postMessage('MyMSG', 'https://*.example.com');
window.opener.postMessage('MyMSG', 'https://(.*)example.com');
不起作用

正确的方法是什么?这可能吗

谢谢

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。注意:示例仅用于解析协议和主机,以获得传递给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.referer,但从安全页面打开非安全url时除外。当您的页面使用https时,当您打开http://url时,将不会设置means document.referer://


谢谢你的澄清。非常有用
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);