Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't pass a function from one window to another in IE

I have a two windows, one is opened from another, so, I have an opener property in "child" window.

Parent window has some function in global scope, which must be called with a function as a first argument (it will be used as a callback).

Both pages are opened from same domain, so, I haven't any Same Origin Policy restrictions (I hope so)...

In a child window I have code like this

if(window.opener) {
    window.opener.myFunction(function() { ... });
}

Everything works fine, until I try to run it in IE. In this browser an argument, received by myFunction, is ALWAYS of type Object (checked with typeof). Code of myFunction is something like this:

window.myFunction = function(cb) {
    alert('Callback type is ' + (typeof cb));
    if(typeof cb == 'function') 
        cb();
    else
        alert('Not a function!');
}

Live demo: http://elifantiev.ru/ie-opener-issue/first.html

The questions is:

  1. is this a standarts compliant behaviour?
  2. is there some workaround for this issue?
like image 489
Olegas Avatar asked May 08 '12 13:05

Olegas


1 Answers

Even though typeof returns "object" the function still works as expected. Calling cb() will execute the function.

An alternative to using typeof to determine if the parameter is a function is testing for the call property which all functions are expected to have:

if (cb && cb.call) { cb(); }

If you are passing along to something that expects a function it can be wrapped like this:

function newCb() {
    return cb.apply(object, arguments);
}

Also note when passing a function from parent to the child the typeof is also object. Comparing original function to function-as-an-object (after the round trip) returns true. This is important if for some reason you need a reference to the original function (for example when unsubscribing).

like image 107
Drew Turner Avatar answered Oct 07 '22 16:10

Drew Turner