如何在另一个窗口中调用函数
node-webkit How to call a function in another window?
我用这段代码创建了一个新窗口,并试图发送一些数据,但函数没有被调用,也许我做错了?
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。这样,您就可以从新窗中的所有函数中访问它。
再次说明:这不是一般用法的正确答案,但它可能适合您的问题。
相关文章:
- 如何从模块链中调用函数.导出到节点中
- 调用函数内部的函数
- 在javascript中调用c函数
- DropDownListFor赢得't在更改时调用函数
- Javascript页面调用函数
- 在动画结束之前调用函数
- 允许父窗口在其不同域的子iframe上调用函数
- 运行Infinite Scroll后调用函数时出现问题
- JavaScript:在调用函数的文本输入上按enter键
- 使用大括号和不使用bracs调用函数的区别
- javascript在事件上调用函数
- 从index.html调用函数,该函数无限循环
- 从带参数的字符串变量调用函数中的函数
- 为什么 JS 不在滚动时调用函数
- 是否可以在不更改上下文的情况下调用函数.apply
- 如何在ES6类中使用参数调用函数
- AngularJS:调用函数时编号不更新
- JavaScript中的立即调用函数表达式(IIFE)-传递jQuery
- 在JavaScript中调用函数时自定义此选项
- 调用函数中声明的变量