【问题标题】:How to call api in top window in the child iframe when they are not the same protocol?当它们不是相同的协议时,如何在子 iframe 的顶部窗口中调用 api?
【发布时间】:2015-05-19 16:31:15
【问题描述】:

我正在使用 nwjs。我在应用页面(顶部窗口)中放了一个 iframe:

<iframe src="aaa.com" id="contentFrame"></iframe>

我想告诉应用页面(顶部窗口)在 iframe(域:aaa.com)中运行一些功能:

<!-- code in the iframe-->
<input type="button" value="close" onclick="window.top.close();"></input>
<input type="button" value="window.top._close" onclick="window.top._close();"></input>

当我在 iframe 中单击上面的按钮时,出现错误:

未捕获的安全错误:阻止了来源为“http://localhost:3900”的框架访问来源为“file://”的框架。请求访问的帧具有“http”协议,被访问的帧具有“文件”协议。协议必须匹配。

我尝试在 package.json 中设置这个参数:

"chromium-args": "--disable-web-security",

但它只适用于“window.to.close();”按钮。

我也想用这种方式调用 Native UI API:

require('nw.gui').gui.Window.get().minimize();

最好的问候。

【问题讨论】:

    标签: google-chrome cross-domain chromium node-webkit


    【解决方案1】:

    我不知道如何允许这样做,但您可以使用Window.postMessage 进行帧之间的安全通信。

     // in parent window
     window.addEventListener("message", function (event) {
        if (event.data == "closeYourSelf") window.close();
     }, false);
    
     // in child iframe
     $('button.close').bind('click', function (clickEv) {
       clickEv.preventDefault();
       window.top.postMessage("closeYourSelf", '*');
     });
    

    【讨论】:

    • 因为这启用了跨域消息传递,除非 OP 希望通过发送消息的任何东西来关闭父窗口,否则父窗口的处理程序需要检查 event.origin 以将消息源列入白名单它允许关闭窗口。
    猜你喜欢
    • 2013-02-16
    • 1970-01-01
    • 2023-04-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-26
    相关资源
    最近更新 更多