gpt4 book ai didi

具有多个子域的 Javascript window.opener.postMessage 跨源

转载 作者:行者123 更新时间:2023-11-28 12:14:46 25 4
gpt4 key购买 nike

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

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。注意示例使用 URL仅解析协议(protocol)和主机以获得传递给 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 时除外。含义document.referrer当您打开http://时不会被设置当您的页面使用 https:// 时的 url

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);

关于具有多个子域的 Javascript window.opener.postMessage 跨源,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52002608/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com