views:

48

answers:

3

My web app includes an ActiveX control. However, when I run the app, I got error "object expected" error intermittently. It seems sometimes the control is not ready when I call its properties/methods. Is there a way that I can detect whether an object is ready using JS?

Thanks a lot.

A: 

If it is your own app, include a readystate event

http://msdn.microsoft.com/en-us/library/aa751970%28VS.85%29.aspx

mplungjan
+1  A: 

If its not you own app, see if you can identify some harmless property or method and then design a wrapper method around the call that tests with try catch if it can access the object, and if yes, call next method in chain (maybe using a delegate to include arguments, and if not ready, use setTimeout to call the wrapper again in say 100 ms.

You might want to include a retry counter to bailout after a few tries so that it's not an infinite loop if the object is broken.

Example:

function TryCallObject(delegate, maxtries, timebetweencalls, failCallback, retrycount)
{
    if(typeof retrycount == "undefined")
        retrycount = 0;
    if(typeof failCallback == "undefined")
        failCallback null;
    try {
        //code to do something harmless to detect if objects is ready
        delegate(); //If we get here, the object is alive
    } catch(ex) {
        if(retrycount >= maxtries)
        {
             if(failCallback != null)
                  failCallback();
             return;
        }
        setTimeout(function () {
              TryCallObject(delegate, maxtries, timebetweencalls, failCallback, retryCount + 1);
            }, timebetweencalls);
    }
}

And its called like this

TryCallObject(function() { /* your code here */ }, 5, 100);

or

TryCallObject(function() { /* your code here */ }, 5, 100, function() {alert("Failed to access ActiveX");});
David Mårtensson