可以在另一个窗口的上下文中调用Javascript方法吗?
假设您有一个全局函数alert2:可以在另一个窗口的上下文中调用Javascript方法吗?,javascript,internet-explorer,Javascript,Internet Explorer,假设您有一个全局函数alert2: function alert2(msg) { window.alert(msg); } 还有对第二个窗口对象的引用: childWindow = window.open(myUrl); 现在,您希望在子窗口的上下文中从窗口调用alert2: alert2.call(childWindow, "does not work without this.window"); 该对话框出现在主窗口中,因为alert2内部的“窗口”绑定到定义此方法的窗口(父窗
function alert2(msg) {
window.alert(msg);
}
还有对第二个窗口对象的引用:
childWindow = window.open(myUrl);
现在,您希望在子窗口的上下文中从窗口调用alert2:
alert2.call(childWindow, "does not work without this.window");
该对话框出现在主窗口中,因为alert2内部的“窗口”绑定到定义此方法的窗口(父窗口)
一种解决方案是修改alert2:
function alert2(msg) {
this.alert(msg);
}
是否可以在不进行此修改的情况下执行此操作?大概是这样的:
alert2.call(childWindow.parent, "no such thing as window.parent");
这是一个人为的例子;childWindow.alert(“”)不是我要找的
我的源代码可以在JSFIDLE上查看和修改,从开始注意:这仅在两个窗口属于同一个域时有效(单域策略) 您可以在
子窗口中创建函数:
var func = function() {
var parent = window; // pointer to parent window
var child = childWindow;
return function() {
... anything you like to do ...
parent.alert('Attached to main window')
child.alert('Attached to child window')
}
}();
childWindow.func = func; // pass function to child window
嵌套函数确保您可以从创建函数的上下文访问引用(注意末尾的}();
,它终止第一个函数并立即调用它)
最后一行在子窗口中创建新函数;子窗口中的所有JavaScript代码也可以通过window.func
访问它
这有点令人困惑,但不妨这样想:您有两个窗口实例/对象。与任何JavaScript对象一样,您可以为它们分配新属性。您可以使用childWindow.opener
获取打开子窗口的窗口
对象
alert2.call(childWindow.opener, "called from child using parent as context");
演示:谢谢……您的代码说明了我对问题的理解。在这种情况下,无法替换上面func()中“child”或“parent”的含义。类似地,似乎无法替代函数中“窗口”的含义,因为创建alert2时捕获“窗口”,就像定义func时捕获“父”和“子”一样。