javascriptrhinonashornjavascript-engine

How can I determine which javascript engine, rhino or nashorn is running my code?


There are several questions how to determine the javascript engine in browser. I have to write javascript code that has to run on rhino and nashorn.

How can I determine if my code is running on rhino or nashorn? Are there typcial functions, variables, constants where you can determine the engine?


Solution

  • Looking at the Rhino to Nashorn migration guide, I see several possible ways.

    If you're not using the Rhino compatibility script, this would do it:

    var usingNashorn = typeof importClass !== "function";
    

    ...since importClass is defined for Rhino but not for Nashorn (unless you include the compatibility script).

    I think Java.type is Nashorn-specific, so:

    var usingNashorn = typeof Java !== "undefined" && Java && typeof Java.type === "function";
    

    You could check for wrapping of exceptions:

    var usingNashorn;
    try {
        // Anything that will throw an NPE from the Java layer
        java.lang.System.loadLibrary(null);
    } catch (e) {
        // false!
        usingNashorn = e instanceof java.lang.NullPointerException;
    }
    

    ...since the migration guide says that will be true for Nashorn but false for Rhino. It does involve throwing an exception, which is unfortunate.