// Java - JavaScript Communication example

Communication between java applets and javascript code is already available since J2SE 1.3 (aka LiveConnect, which was btw. rewritten from scratch in Java 6 update 10 as part of the new plugin) and is really easy to implement. It is a simple way to break out of the sandbox and do things which would usually require full system access (a signed applet + user approval via security dialog). For example applets living in a sandbox are only allowed to read mouse events via the AWT/Swing event mechanism which works as long the mouse is over the applet.

To read e.g the mouse position globaly you would need to call MouseInfo.getPointerInfo().getLocation() which would cause a java.security.AccessControlException: access denied. However, in javascript it is trivial to track mouse events for the whole html document (e.g google adds track onclick x,y events).

All you have to do is to use the object tag instead of applet tag (which is deprecated anyway) and give the object (applet) a name via the id attribute.

<form name="FishForm">   
<object width="256" height="256" type="application/x-java-applet" id="CrazyFish">
<param value="http://people.fh-landshut.de/~mbien/weblog/java_js_interop/launch.jnlp" name="jnlp_href" />
<param value="false" name="draggable" />
</object>
</form>

 now you can simply call methods as usual.

<script language="JavaScript1.2">
//...
document.onmousemove = onMouseMoved;

var tempX = 0;
var tempY = 0;

var applet = document.FishForm.CrazyFish;

function onMouseMoved(e) {
//...
// javascript -> java calls
applet.jsObjectOrigin(findPosX(applet), findPosY(applet));
applet.jsMouseMoved(tempX, tempY)
return true
}
//...
</script>

 the other side is a plain old public method implemented in the java applet.

    /**
* called from javascript.
*/
public void jsMouseMoved(int x, int y) {
//do something usefull
}

 RIA/Web2.0 Observer Pattern in action ;)

(The applet won't work with JRE version < 1.6 update 10 (or the equivalent on Mac OS) since I used the jnlp deployment mechanism, but it wouldn't have been necessary for this particular applet)

... and never forget Web 2.0 is watching you




Comments:

Post a Comment:
  • HTML Syntax: NOT allowed