简体   繁体   中英

How to call window.atob() javascript function from java code?

I am trying to use rhino. I want to use window.atob(param) javascript function from java code. First of all is it possible? This is what I have tried.

ScriptEngine runtime = null;
try {
    runtime = new ScriptEngineManager().getEngineByName("javascript");
    runtime.put(
            "str",
            "PGh0bJvZHk+PC9odG1sPg==");
    System.out.println((String)runtime.eval("window.atob(str)"));

} catch (Exception ex) {
    ex.printStackTrace();
}

I am getting the following exception.

sun.org.mozilla.javascript.internal.EcmaError: ReferenceError: "window" is not defined

I know I can decode using java but can any one let me know how to do it using rhino?

window (and document , while we're at it) are objects that are tied to a web page in a browser. These concepts don't exist within Rhino so you can't access any of the window 's methods.

There is a request on github to add support for atob though. Until then you'll have to implement it yourself or find a library that has it.

As Vache wrote, the window object only exists in browsers. However, you can simulate a browser using env.js .

After loading this script, you get access to the window object.

Thanks to @feuerball. I have found the solution to my problem after going through SO and Docs.

Here is the code sample:

        import org.mozilla.javascript.Context;
        import org.mozilla.javascript.ContextFactory;
        import org.mozilla.javascript.tools.shell.Global;
        import org.mozilla.javascript.tools.shell.Main;
        .................
        Context cx = ContextFactory.getGlobal().enterContext();
        cx.setOptimizationLevel(-1);
        cx.setLanguageVersion(Context.VERSION_1_5);
        Global global = Main.getGlobal();
        global.init(cx);
        try {
            Main.processSource(cx, "C:\\Desktop\\env.rhino.1.2.js");
            System.out.println(cx.evaluateString(global, "window.atob(\"UmYXNlahcg==\")", "js", 1, null));
        } catch (IOException e) {
            e.printStackTrace();
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM