Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I embed a Java applet dynamically with Javascript?

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);
}
like image 885
Jonathan Avatar asked Jul 15 '10 19:07

Jonathan


People also ask

Can you call a Java applet using a JavaScript function?

Javascript can talk to Java applet in the same HTML page through LiveConnect technology. We can write Javascript code to invoke methods (including arguments) and access objects which are exposed by the applet.

Can we develop applet using JavaScript?

Of course you can also write your own applets from scratch as discussed in this tutorial on programming in JavaScript.

Can a Java applet be executed from a Web browser?

A Java applet can be executed from a Web browser. The class name must be the same as the file name that contains the class. A file may contain several classes. Each class in the file is compiled into a separate bytecode file.


1 Answers

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.

like image 166
Beachhouse Avatar answered Oct 24 '22 11:10

Beachhouse