views:

51

answers:

1

I want to be able to insert a Java applet into a web page dynamically using a Javascript function that is called when a button is pressed. (Loading the applet on page load slows things down too much, freezes the browser, etc...) I am using the following code, which works seamlessly in FF, but fails without error messages in IE8, Safari 4, and Chrome. Does anyone have any idea why this doesn't work as expected, and how to dynamically insert an applet in a way that works in all browsers? I've tried using document.write() as suggested elsewhere, but calling that after the page has loaded results in the page being erased, so that isn't an option for me.

function createPlayer(parentElem)
{
    // The abc variable is declared and set here

    player = document.createElement('object');
    player.setAttribute("classid", "java:TunePlayer.class");
    player.setAttribute("archive", "TunePlayer.class,PlayerListener.class,abc4j.jar");
    player.setAttribute("codeType", "application/x-java-applet");
    player.id = "tuneplayer";
    player.setAttribute("width", 1);
    player.setAttribute("height", 1);

    param = document.createElement('param');
    param.name = "abc";
    param.value = abc;
    player.appendChild(param);

    param = document.createElement('param');
    param.name = "mayscript";
    param.value = true;
    player.appendChild(param);

    parentElem.appendChild(player);
}
+1  A: 

I would have suggested doing something like what you're doing; so I'm baffled as to why it's not working.

Here's a document that looks pretty authoritative, coming from the horse's mouth as it were. It mentions the idiosyncrasies of different browsers. You may end up needing to do different tag soups for different implementations.

But maybe there's something magic about applet/object tags that keeps them from being processed if inserted dynamically. Having no more qualified advice, I have a crazy workaround to offer you: Howzabout you present the applet on a different page, and dynamically create an IFRAME to show that page in the space your applet should occupy? IFRAMEs are a bit more consistent in syntax across browsers, and I'd be surprised if they were to fail the same way.

Maybe you should use your browser's debugging tools to look at the DOM after you swap in your applet node. Maybe it's not appearing where you think it is, or not with the structure you think you're creating. Your code looks OK to me but I'm not very experienced with dynamic applets.

Carl Smotricz
Hi,Thanks for your suggestions! The IFrame idea is a good one, and I'll probably use that if I can't get the dynamic insertion to work. I did look at the DOM in IE after inserting the applet, and it's very strange. When inserting the applet, I can see the containing div expand somewhat to accommodate the applet, but the code never appears in the DOM, and the applet is never executed. I have no idea why this happens...
Jonathan