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

前端 未结 2 1984
予麋鹿
予麋鹿 2020-12-19 02:49

Say you have a global function alert2:

function alert2(msg) {
    window.alert(msg);
}

And you also have a reference to a second window obj

相关标签:
2条回答
  • 2020-12-19 03:06

    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.

    0 讨论(0)
  • 2020-12-19 03:15

    You can use childWindow.opener to get the window object that opened the child window.

    alert2.call(childWindow.opener, "called from child using parent as context");
    

    Demo: http://jsfiddle.net/hJ7uw/8/

    0 讨论(0)
提交回复
热议问题