【问题标题】:node-webkit How to call a function in another window?node-webkit 如何在另一个窗口中调用函数?
【发布时间】:2014-08-29 13:56:14
【问题描述】:

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

index.html 上的 script.js

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 上的 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)

【问题讨论】:

  • 您可以将参数附加到 URL,例如 GET 请求:listdir.html?param1=value1&amp;param2=value2
  • 是的,我当然可以这样做,我只是期待有一种更动态的方式。
  • 您可以使用“全局”变量在窗口之间共享任何内容,包括函数。 github.com/rogerwang/node-webkit/wiki/…

标签: javascript windows node.js node-webkit


【解决方案1】:

好的,这可能不是问题“如何在另一个窗口中调用函数”的正确答案,而是您最初的问题“如何将参数发送到新窗口”的答案(在编辑标题之前)。

由于我是 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(参见documentation 这里)需要脚本的源代码,可以在新创建的窗口的上下文中运行。我想,您的第一次尝试没有成功,因为脚本将在创建窗口的那一刻执行,因此 DOM 尚未解析,并且此时没有可用的 JavaScript 函数。所以只有基本功能可用(window 对象)。因此,我们传入了一个函数,该函数将在 window.sessionStorage 中存储序列化的 JSON。这样,您就可以从新窗口中的所有功能访问它。

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

【讨论】:

  • 你说得对,在 DOM 完全加载之前调用了 Window.eval,我听了 document-end 事件,现在一切正常,谢谢 :)
猜你喜欢
  • 1970-01-01
  • 2013-12-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-12-09
  • 1970-01-01
  • 2014-01-23
  • 1970-01-01
相关资源
最近更新 更多