No-argument method on window.external is invoked when checking with typeof

Posted by janko on Stack Overflow See other posts from Stack Overflow or by janko
Published on 2010-05-09T14:23:31Z Indexed on 2010/05/09 14:28 UTC
Read the original article Hit count: 188

Filed under:
|
|

Hi,

I am trying to display an HTML page with embedded JavaScript code inside a System.Windows.Forms.WebBrowser control. The JavaScript code is expected to interact with the embedding environment through the window.external object. Before invoking a method on window.external, JavaScript is supposed to check for the existance of the method. If it is not there, the code should invoke a generic fallback method.

// basic idea
if (typeof(window.external.MyMethod) != 'undefined') {
    window.external.MyMethod(args);
} else {
    window.external.Generic("MyMethod", args);
}

However, checking for a no-argument method with typeof seems to invoke the method already. That is, if MyMethod accepts any positive number of arguments, the code above will work perfectly; but, if MyMethod is a no-argument method, then the expression typeof(window.external.MyMethod) will not check for its type but invoke it, too.

Is there any work-around to this behavior? Can I somehow escape the expression window.external.MyMethod to prevent the method call from occurring?

© Stack Overflow or respective owner

Related posts about JavaScript

Related posts about c#