Skip to content

Instantly share code, notes, and snippets.

@georules
Created May 9, 2016 19:04
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save georules/daf05188c510b84460992caf1979d61c to your computer and use it in GitHub Desktop.
Save georules/daf05188c510b84460992caf1979d61c to your computer and use it in GitHub Desktop.
<!-- Include the Polyfill -->
<script src="https://www.javapoly.com/javapoly.js"></script>
<script type = "text/java" src="rhino1.7.7.1/lib/rhino-1.7.7.1.jar"></script>
<!-- Write your Java code -->
<script type="text/java">
package com.demo;
import com.javapoly.dom.Window;
import java.lang.String;
import org.mozilla.javascript.Context;
import org.mozilla.javascript.Scriptable;
import org.mozilla.javascript.ScriptableObject;
public class HelloWorld
{
public static void sayHello()
{
Window.alert("Hello World, from Java!");
String x = "";
String script = "x = \"Hello from JS\";";
Context cx = Context.enter();
try {
Scriptable scope = cx.initStandardObjects();
Object wrapped = Context.javaToJS(x, scope);
ScriptableObject.putProperty(scope,"x",wrapped);
cx.evaluateString(scope, script, "Script", 1, null);
x = Context.toString(scope.get("x", scope));
} catch( Exception e) {
e.printStackTrace();
} finally {
Context.exit();
}
Window.alert(x);
}
}
</script>
<!-- Invoke your Java code from Javascript -->
<script type="text/javascript">
com.demo.HelloWorld.sayHello();
</script>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment