tags:

views:

56

answers:

2

Is it possible to copy a function (or any object for that matter) from one window context to another in Javascript?

Let's say I have a parent window with a frame in it. The frame defines a function foo(), which I'd like to copy to the outer window. (One reason to do it would be so that foo() is available when the frame document navigates to a different URL.)

I know I can easily create a reference to foo() in the parent by doing

function foo() { ... }    
parent.foo = foo;

But with this method foo() still lives in the frame document, and will not be available to the parent should frame get unloaded.

I know I can also create a new function in the parent by using the Function constructor:

parent.foo = new parent.Function(" ... ");

However, this requires me to have my function as a JS string.

DOM supports moving nodes from one document to another via importNode(). Does Javascript have a similar feature?

A: 

You can always get the code for a given function calling it's toString() method:

parent.foo = new parent.Function( originalFunction.toString() );

Though I don't certainly know it's available in every browser, I think I've seen it working in major browsers, modern versions.

the toString returns "function(){ ... }", so this won't
Marius
work. Sorry, my keyboard is working weirdly.
Marius
A: 

nitko's solution seems to be correct, though a little more work is required. This function seems to work on FF2, FF3, IE7 and Chrome:

  function importFunction(fn, win) {
    var code = fn.toString();
    var params = code.match(/\(([^)]*)\)/);
    if (typeof(params[1]) !== 'undefined') {
      params = params[1].split(/\s*,\s*/);
    } else {
      params = null;
    }
    code = code.replace(/^[^{]*{/, '');
    code = code.replace(/}$/, '');
    if (params) {
      return new win.Function(params, code);
    } 
    return new win.Function(code);
  }

The returned function can be used in the needed window. Something like:

parent.foo = importFunction(foo, parent);
levik