如何在另一个窗口中调用函数

node-webkit How to call a function in another window?

本文关键字:调用 函数 窗口 另一个      更新时间:2023-09-26

我用这段代码创建了一个新窗口,并试图发送一些数据,但函数没有被调用,也许我做错了?

script.js on index.html

var path = require('path');
element.onclick = function(){
    var win = gui.Window.get(window.open('listdir.html'));
    var location = path.resolve(process.cwd(),'fontsFolder');
    win.eval(null, 'listdir("'+location+'")'); //Is there a node function to parse '''?
};

listdir.js on listdir.html

function listdir(directory){
    alert("directory "+directory); //never called
}
错误:

ReferenceError: listdir is not defined
    at <anonymous>:1:1
    at Window.init.Window.eval (window_bindings.js:486:16)
    at HTMLLIElement.element.onclick (file:///C:/../AppData/Local/Temp/nw3528_1882/js/script.js:29:12)

好吧,这可能不是正确的回答问题"如何在另一个窗口调用函数",但你的初始问题的答案"如何发送参数到新窗口"(在编辑标题之前)。

由于我是HTML5中新存储对象的狂热爱好者,我将在sessionStorage上同步窗口(因此所有传递的参数将在当前新窗口生命周期内存活,但之后就不存在了)。

我的工作解决方案:

index.html(初始窗口)

<!DOCTYPE html>
<html>
<body>
    Test <a href="">Click</a>
    <script src="jquery-1.11.1.min.js"></script>
    <script>
        var mySharedObj = {
            'one': 1,
            'two': 2,
            'three': 3
        };
        // node-webkit specific
        var gui = require('nw.gui');
        $('a').click(function() {
            var win = gui.Window.get(window.open('index2.html'));
            win.eval(null, 'sessionStorage.setItem(''mySharedJSON'', '''+JSON.stringify(mySharedObj)+''');');
        });
    </script>
</body>

index2.html(通过window.open调用打开的新窗口:

<!DOCTYPE html>
<html>
<body>
    Test 2: 
    <script src="jquery-1.11.1.min.js"></script> 
    <script>
        $(document).ready(function() {
            // Process sharedObj when DOM is loaded
            var mySharedObj = JSON.parse(sessionStorage.getItem('mySharedJSON'));
            // Now you can do anything with mySharedObj
            console.log(mySharedObj);
        });
    </script>
</body>

它是如何工作的呢?window.eval(参见这里的文档)需要脚本的源代码,可以在新创建的窗口的上下文中运行。我猜,你的第一次尝试没有工作,因为脚本将在窗口创建的那一刻执行,因此DOM尚未解析,没有JavaScript函数在那一刻可用。因此只有基本功能可用(window对象)。因此,我们传入一个函数,它将在window.sessionStorage中存储序列化的JSON。这样,您就可以从新窗中的所有函数中访问它。

再次说明:这不是一般用法的正确答案,但它可能适合您的问题。