Node-webkit iframe访问父nw函数

时间:2015-02-05 10:30:48

标签: javascript node.js iframe node-webkit nw.js

我开发了一个简单的nw.js(ex node-webkit)应用程序。 它会打开一个带有属性

的全屏幕iframe
  

nwfaketop

在这个iframe中(逻辑上在不同的域中)我需要调用父nodejs函数。 我能怎么做? 这是我的index.html主要nw.js app的代码:

<html>
<body style="margin:0">
<iframe src="https://www.mydomain.it/test.html" style="width:100%;height:100%;border:0;padding:0" nwfaketop></iframe>
<script>
    var gui = require('nw.gui');
    var win = gui.Window.get();
    win.showDevTools();
    var clipboard = gui.Clipboard.get();

    function copy_do(text){
        clipboard.set(text, 'text');
    }

    onload = function() {
        win.maximize();
    }
</script>
</body>
</html>

这里的代码位于https://mydomain.it/test.html

上的iframe中
<!doctype html>
<html lang="it">
<head>
    <meta charset="UTF-8">
    <title>Test page</title>
</head>
<body>
<div style="text-align: center;">Test page</div>
<script>
parent.copy_do("stackoverflow");
</script>
</body>
</html>

如你所见,我需要调用函数

  

copy_do();

来自父主文件。

我该怎么办? 提前致谢

2 个答案:

答案 0 :(得分:1)

您可以将主应用程序中的回调函数注册到iframe的内容窗口中。然后从iframe调用该函数。 例如:

在您的主要应用程序中:

function copy_do(text){
    clipboard.set(text, 'text');
}

var iframe = document.getElementsByTagName('iframe')[0];
iframe.onload = function(){
   iframe.contentWindow.myCallback = copy_do;
}
在您的iframe脚本中

window.myCallback('sometext');

答案 1 :(得分:0)

试试这个。 onload()的功能无法捕获子文档的完整状态。 请检查文档就绪状态是否“完成”。

<iframe id="ifrmChild" src="http://yourdomain/iframe.html" style="width:100%;height:100%;border:0;padding:0" nwfaketop></iframe>

<script>

    window.doit = function(text){
        console.log('Hey!!!!!');
    }

    var interval = setInterval(function () {
        var iframe = document.getElementById("ifrmChild");
        var cw = iframe.contentWindow;
        if (cw.document.readyState == "complete")
        {
        clearInterval(interval);
        iframe.contentWindow["doit"] = window.doit;
        iframe.contentWindow.eval("doit('ssss');");

    }
});