Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
465 views
in Technique[技术] by (71.8m points)

internet explorer - Possible to call a Javascript method in the context of another window?

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);

Now you want to call alert2 from window in the context of the childWindow:

alert2.call(childWindow, "does not work without this.window");

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).

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");

This is a contrived example; childWindow.alert("") isn't what I'm looking for!

My source can be seen and modified on jsfiddle starting with http://jsfiddle.net/hJ7uw/2/

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Note: This only works if both windows belong to the same domain (Single Domain Policy).

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).

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.

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...