节点webkit iframe访问父nw函数



我开发了一个简单的nw.js(ex node webkit)应用程序。它打开一个具有属性的全屏Iframe

nwfaketop

在这个iframe中(逻辑上在不同的域中),我需要调用一个父nodejs函数。我该怎么办?这里是我的index.html主nw.js应用程序的代码:

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

这里的代码在iframe上https://mydomain.it/test.html

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

来自父主文件。

我该怎么办?提前感谢

您可以将主应用程序中的回调函数注册到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');

试试这个。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');");
    }
});

最新更新