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);
}
document.write()
Will overwrite your entire document. If you want to keep the document, and just want an applet added, you'll need to append it.
var app = document.createElement('applet');
app.id= 'Java';
app.archive= 'Java.jar';
app.code= 'Java.class';
app.width = '400';
app.height = '10';
document.getElementsByTagName('body')[0].appendChild(app);
This code will add the applet as the last element of the body tag. Make sure this is run after the DOM has processed or you will get an error. Body OnLoad, or jQuery ready recommended.