我用这段代码创建了一个新窗口并尝试发送一些数据但是没有调用该函数,也许我做错了?
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.html 上的 listdir.js
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
(请参阅此处的 documentation)需要脚本的源代码,这些脚本可能会在新创建的窗口的上下文中运行。我想,您的第一次尝试没有成功,因为脚本将在窗口创建的那一刻执行,因此 DOM 尚未解析,此时没有可用的 JavaScript 函数。所以只有基本功能可用(window
对象)。所以我们传入一个函数,它将在 window.sessionStorage 中存储序列化的 JSON。这样,您就可以从新窗口中的所有功能访问它。
再次声明:这不是一般用法的正确答案,但它可能适合您的问题。
关于javascript - node-webkit 如何在另一个窗口中调用一个函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24638464/