Move all functions to child window

183 Views Asked by At

If I do this:

var new_win = window.open();

How do I make it so that all of the functions that could be used in the parent window can now be used in the child window (new_win)?

I do not want to do:

var fun1 = window.opener.fun1;
var fun2 = window.opener.fun2;
...
3

There are 3 best solutions below

5
On BEST ANSWER

Please note that what follows is a dangerous, dirty, messy, M$-level hack. I am fully aware of this, but it (theoretically) does what @Neal wants. (I'm a little scared to even post it, and I fully expect downvotes)

var i, w = window.opener;
for (i in w)
{
    if (w.hasOwnProperty(i) && !window.hasOwnProperty(i) && typeof w[i] === 'function')
    {
        window[i] = w[i];
    }
}

In light of the scope issues, I've determined that we must use .bind. There is a shim at the MDN Entry for Function.bind which will be necessary for certain browsers.

Please note that before using .bind, the code must check to see if the property is a function. I have done this along with the hasOwnProperty checks, but if you wish to transfer values as well as functions, you may want to do this within its own if statement.

var i, w = window.opener;
for (i in w)
{
    if (w.hasOwnProperty(i) && !window.hasOwnProperty(i) && typeof w[i] === 'function')
    {
        window[i] = w[i].bind(window);
    }
}
0
On

You could create an new instance of a function and pass the function name and optional argNs something like as follows

var parentFunction = new Function("name", "args", "return (window.opener != null) ?  opener.window[name](args) : false");

parentFunction('notification','waring, red, 2');
0
On

First off, I would create a namespace (helps avoid function collisions) and then I would just reference it in the popup window.

parent window:

MyNameSpace = {
      // put functions, classes or whatever you want in here.
};

in the pop-up window:

MyNameSpace = window.opener.MyNameSpace;

The only issue potentially with what you're asking for is if the function you call is trying to reference the window object. I would pass a window object to any functions that manipulate a window.

e.g.

function (arg1, arg2, argn, windowHandle) {
      windowHandle = windowHandle || self;

      // do some stuff.

}