Checking if a function is defined in the IE8 popup window

I have a popup that allows the opening window to optionally define a callback function that, if defined, will be called when the user executes the popup. Based on the tips I read, I do this:

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

This works great in Firefox - when a function is defined, typeof is a "function" as intended. However, in IE8, typeof is an "object." A function is usually defined in an opener, for example:

 function callbackFunction() { ... } 

Does anyone know why typeof will be different in IE8? I am also open to other suggestions on how to do this. I also tried if (window.opener && window.opener.callbackFunction) , but this caused IE8 to explode when the function was not defined.

+4
source share
2 answers

You can try

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

I donโ€™t have IE right now, so I canโ€™t verify this, but I believe that it will work.

+6
source

This is a hack, but it 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. For some native browser functions, such as alert (), it will fail.

0
source

Source: https://habr.com/ru/post/1347934/


All Articles