Search code examples
javascriptnashorn

Calling Java from JavaScript with Nashorn


I have a Chrome extension project where I should make a call to Java function from my JavaScript source file. I'm trying to use Nashorn for this purpose, But in the following line:
var MyJavaClass = Java.type('my.package.MyJavaClass');
I'm getting the following error

Uncaught ReferenceError: Java is not defined


Solution

  • Nashorn is a Java library which can be used to add support for JavaScript to a program written in Java.

    It is not a feature built into the JavaScript language.

    It is not a feature built into Chrome.

    You cannot use Nashorn from a Chrome extension.

    Chrome has no mechanism to allow JavaScript to invoke Java code.

    Chrome doesn't even support Java as a plugin any more.


    There are two basic approaches you can take to run my.package.MyJavaClass from Chrome:

    • Rewrite my.package.MyJavaClass in JavaScript
    • Wrap my.package.MyJavaClass in a web service (e.g. using a Servlet) and then access it via Ajax (fetch / XMLHttpRequest).