I don’t like applet… and I don’t like javascript. But some time you just need to use them. It is bad if it happens but even worse if you have to make them communicate to each other.
Java Script call applet function
JavaScript can call applet function. Suppose we have an applet with name “appletsample” and main class have a public method name register()
public Main extend Applet {
public void start() {
-- applet code --
}
public void register() {
-- do something here --
}
}
We can call register() from javascript like this:
document.appletsample.register();
Just remember that the code that is called from applet is working on different context, which means:
- We have to work with security issue
- If the code generate UI, it will use standard Look&Feel of the OS
To work around the security issue, there is two suggestions can be chosen:
- javascript only change a boolean variable, and create one thread that check this variable all the time, and if there is some changes, trigger the real action which need security permission.
public Main extend Applet implements Runnable {
boolean generate = false;
public void start() {
Thread thread = new Thread(this);
thread.start();
-- applet code --
}
public void register() {
generate = true;
}
public void run() {
while (true) {
if (generate) {
-- do something here --
}
}
}
}
- wrap the code that needs security permission by java.security.PrivilegedAction
Example:
public Main extend Applet {
public void start() {
-- applet code --
}
public void register() {
AccessController.doPrivileged(new PrivilegedAction() {
public Object run() {
-- do something here --
}
});
}
}
The first solution, however, takes a lot of CPU processes, where in a while, will also solve problem with Look&Feel. The second solution is not solving the Look&Feel problem, but uses CPU efficiently.
Call javascript from applet
We need classes from netscape. This is located in file plugin.jar, you can find it in JRE-DIR/lib/. After you find the file, include it with your application classpath. Then write code in your applet like this:
JSObject win = (JSObject) JSObject.getWindow(this);
(String) win.eval("alert('test javascript');");
Change alert(’test javascript’); to whatever javascript code you want to call from applet.