admin管理员组

文章数量:1323689

I have a pop-up that allows the opener window to optionally define a callback function, which if defined will be called when the user is done with the pop-up. Based on the advice I've read I'm doing this:

if (window.opener && (typeof window.opener.callbackFunction == 'function')) {
  window.opener.callbackFunction()
}

This works fine in Firefox - when the function is defined, the typeof is "function" as intended. However, in IE8 the typeof is "object" instead. The function is defined normally in the opener, like so:

function callbackFunction() {
  ...
}

Does anybody know why the typeof would be different in IE8? I'm also open to other suggestions as to how to acplish this. I also tried if (window.opener && window.opener.callbackFunction) but that caused IE8 to blow up when the function wasn't defined.

I have a pop-up that allows the opener window to optionally define a callback function, which if defined will be called when the user is done with the pop-up. Based on the advice I've read I'm doing this:

if (window.opener && (typeof window.opener.callbackFunction == 'function')) {
  window.opener.callbackFunction()
}

This works fine in Firefox - when the function is defined, the typeof is "function" as intended. However, in IE8 the typeof is "object" instead. The function is defined normally in the opener, like so:

function callbackFunction() {
  ...
}

Does anybody know why the typeof would be different in IE8? I'm also open to other suggestions as to how to acplish this. I also tried if (window.opener && window.opener.callbackFunction) but that caused IE8 to blow up when the function wasn't defined.

Share edited Apr 13, 2011 at 15:49 Andrew K asked Apr 13, 2011 at 15:18 Andrew KAndrew K 5612 gold badges6 silver badges16 bronze badges 1
  • Correction: simply checking for the existence of window.opener.callbackFunction does work, it was another bug that broke that. Technically it's not ideal though since it doesn't confirm that it's really a function. – Andrew K Commented Apr 13, 2011 at 16:11
Add a ment  | 

2 Answers 2

Reset to default 7

You can try

if ( window.opener && (typeof window.opener.callbackFunction != 'undefined') {
  window.opener.callbackFunction();
}

I don't have IE currently so I can not test this but believe it will work.

It's a hack, but this will work:

if (typeof window.opener.callbackFunction == 'object') {
   // this first 'if' is required because window.opener returns an object even
   // if window.opener has been closed
   if(window.opener.callbackFunction.toString().substr(0,8) == 'function') {
      window.opener.callbackFunction();
   }
}

Note: It will fail for some native browser functions like alert().

本文标签: javascriptChecking if a function is defined in the opener window in IE8Stack Overflow