views:

965

answers:

3

Hi,

This doesn't work in Safari:

<html>
<body>
<applet id="MyApplet" code="MyAppletClass" archive="MyApplet.jar">
<script type="text/javascript">
   alert(document.getElementById('MyApplet').myMethod);
</script>
</body>
</html>

myMethod is a public method declared in MyAppletClass.

When I first load the page in Safari, it shows the alert before the applet has finished loading (so the message box displays undefined) . If I refresh the page, the applet has already been loaded and the alert displays function myMethod() { [native code] }, as you'd expect.

Of course, this means that the applet methods are not available until it has loaded, but Safari isn't blocking the JavaScript from running. The same problem happens with <body onLoad>.

What I need is something like <body onAppletLoad="doSomething()">. How do I work around this issue?

Thanks

PS: I'm not sure if it's relevant, but the JAR is signed.

+1  A: 

I use a timer that resets and keeps checking a number of times before it gives up.

var applet = document.getElementById('MyApplet');

function performAppletCode(count) {
    if (!applet.myMethod && count > 0) {
       setTimeout( function() { performAppletCode( --count ); }, 2000 );
    }
    else if (applet.myMethod) {
       // use the applet for something
    }
    else {
       alert( 'applet failed to load' );
    }
}  

performAppletCode( 10 );

Note that this assumes that the applet will run in Safari. I've had some instances where an applet required Java 6 that simply hangs Safari even with code similar to the above. I chose to do browser detection on the server and redirect the user to an error page when the browser doesn't support the applet.

tvanfosson
Thank you. It's a shame there isn't a cleaner way of doing this!
Pedro d'Aquino
A: 

@tvanfosson: thanks a lot, this addressed similar problem i had

A: 

Hi

I had a similar problem some time ago and adding MAYSCRIPT to the applet tag solved my problem.

Take a peek at this page: http://www.htmlcodetutorial.com/applets/%5FAPPLET%5FMAYSCRIPT.html

Hope it helps!

Bruno
I don't see how this is relevant to waiting for the applet to load. Also, the example on the page doesn't work in Firefox 3.5.4 on Snow Leopard.
edoloughlin