Use your Java classes in the browser with JavaPoly.js
Java has always been usable in the browser since its creation. However, the browser needed the specific Java plugin to execute Java applications that was packaged inside applets. Then, a more flexible solution was created with Java Web Start but finally, it was always based on the applet technology. With the end announced of plugins support in browsers like Chrome or Firefox, a solution must be found to execute Java code directly in the browser. Some great developers have already started to work on a replacement solution named JavaPoly.js.
JavaPoly.js is a new library, available on https://www.javapoly.com, that polyfills native Java Virtual Machine support in the browser. Actually, it supports just Chrome and Firefox browsers and is not considered as stable but it’s promising. JavaPoly.js lets you to import your existing Java classes, and invoke them directly from Javascript. Even better, there is no need to have Java installed on the user computer. With JavaPoly.js, Java becomes a first class citizen by running in the browser’s script tags, with the possibility to interact directly with the DOM, instead of being encapsulated in an applet sandbox.
All you need to try JavaPoly.js is to import the javapoly.js library that is here : https://www.javapoly.com/javapoly.js . Your first “Hello World” program will be like that :
<!-- Include the Polyfill --> <script src="https://www.javapoly.com/javapoly.js"></script> <!-- Write your Java code --> <script type="text/java"> package com.ssaurel; import com.javapoly.dom.Window; public class HelloWorld { public static void sayHello(String name) { Window.alert("Hello " + name + ", from Java !"); } } </script> <!-- Invoke your Java code from Javascript --> <script type="text/javascript"> com.ssaurel.HelloWorld.sayHello("SSaurel"); </script>
JavaPoly.js allows you to import and use most Java libraries. For example, you can imagine to package your HelloWorld sample class in a jar. Note that you can also import directly the .class file or even the Java source code file. If you want to include an HelloWorld.jar, you could use the following code :
<!-- Include the Polyfill --> <script src="https://www.javapoly.com/javapoly.js"></script> <!—Include HelloWorld.jar --> <script type="text/java" src="http://www.ssaurel.com/HelloWorld.jar"></script> <!-- Invoke your Java code from Javascript --> <script type="text/javascript"> com.ssaurel.HelloWorld.sayHello("SSaurel"); </script>
Since Javascript is singe-threaded and Java applications can be multithreaded, all calls to JVM must be asynchronous. Thus, the return value of a Javascript call to Java code will always be a promise.
The JavaPoly.js project is still very young but looks really promising with a lot of possibilities in the future. It can be a good idea to keep an eye on it and why not try it today !
Leave a Reply
You must be logged in to post a comment.