【问题标题】:Javascript window.opener.postMessage Cross Origin with multiple sub domains具有多个子域的 Javascript window.opener.postMessage 跨域
【发布时间】:2019-01-30 19:48:29
【问题描述】:

我正在尝试允许多个子域:

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

无效

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

谢谢

【问题讨论】:

    标签: javascript cross-domain postmessage multiple-domains


    【解决方案1】:

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

    【讨论】:

    • 感谢您的澄清。很有用
    猜你喜欢
    • 1970-01-01
    • 2014-07-13
    • 2012-12-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-08-28
    • 2011-03-15
    相关资源
    最近更新 更多