可以在另一个窗口的上下文中调用Javascript方法吗? [英] Possible to call a Javascript method in the context of another window?
问题描述
假设你有一个全局函数alert2:
Say you have a global function alert2:
function alert2(msg) {
window.alert(msg);
}
您还可以引用第二个窗口对象:
And you also have a reference to a second window object:
childWindow = window.open(myUrl);
现在你想在childWindow的上下文中从窗口调用alert2:
Now you want to call alert2 from window in the context of the childWindow:
alert2.call(childWindow, "does not work without this.window");
对话框出现在主窗口中,因为alert2内的窗口绑定到窗口中定义了这个方法(父窗口)。
The dialog box appears in the main window because "window" inside of alert2 is bound to the window in which this method was defined (the parent window).
一种解决方案是修改alert2:
One solution is to modify alert2:
function alert2(msg) {
this.alert(msg);
}
如果没有这个修改,是否可以这样做?这样的事情:
Is it possible to do this without this modification? Something like this:
alert2.call(childWindow.parent, "no such thing as window.parent");
这是一个人为的例子; childWindow.alert()不是我想要的!
This is a contrived example; childWindow.alert("") isn't what I'm looking for!
我的源码可以在jsfiddle上看到和修改,以 http://jsfiddle.net/hJ7uw/2/
My source can be seen and modified on jsfiddle starting with http://jsfiddle.net/hJ7uw/2/
推荐答案
注意:这仅适用于两个窗口属于同一个域(单域策略)的情况。
Note: This only works if both windows belong to the same domain (Single Domain Policy).
您可以做的是创建函数 childWindow
:
What you can do is create function in the childWindow
:
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
嵌套函数确保您可以从上下文访问引用创建函数的位置(注意}();
在结尾处终止第一个函数并立即调用它。)
The nested functions make sure that you can access the references from the context where the function was created (note the }();
at the end which terminates the first function and calls it immediately).
最后一行在子窗口中创建新函数;子窗口中的所有JavaScript代码都可以以 window.func
的形式访问它。
The last line creates the new function in the child window; all JavaScript code in the child window can access it as window.func
, too.
这有点令人困惑但是只需这样想:你有两个窗口实例/对象。就像任何JavaScript对象一样,您可以为它们分配新的属性。
It's a bit confusing but just think of it like this: You have two window instances/objects. Just like with any JavaScript object, you can assign new properties to them.
这篇关于可以在另一个窗口的上下文中调用Javascript方法吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!