Can J2V8 execute anonymous function?

365 views Asked by At

I'm trying to execute this piece of javascript code

(function() {
    var z = '';
    var b = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
    for (var i = 0; i < b.length; i += 2) {
        z = z + parseInt(b.substring(i, i + 2), 16) + ',';
    }
    z = z.substring(0, z.length - 1);
    eval(eval('String.fromCharCode(' + z + ')'));
})();

but I got this error:

undefined:1: ReferenceError: document is not defined

If I assign the function to a variable, I haven't neither error nor result.

var a = function() {
    var z = '';
    var b = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
    for (var i = 0; i < b.length; i += 2) {
        z = z + parseInt(b.substring(i, i + 2), 16) + ',';
    }
    z = z.substring(0, z.length - 1);
    eval(eval('String.fromCharCode(' + z + ')'));
};

Have you got any idea on how run this script with J2V8? Thank you in advance

1

There are 1 answers

0
irbull On

I'll be honest, I don't know what the JS is supposed to do. You have an eval wrapped in an eval, and the function has no return statement. Plus, xxxxx doesn't appear to be a valid input.

Having said all that, if I remove the wrapped eval, use a number for the the variable b and return the result, it works fine for me.

@Test public void testExample2() { String jsCode = "(function() {\n" + "var z = '';\n" + "var b = '12345678';\n" + "for (var i = 0; i < b.length; i += 2) {\n" + " z = z + parseInt(b.substring(i, i + 2), 16) + ',';\n" + "}\n" + "z = z.substring(0, z.length - 1);\n" + "return eval('String.fromCharCode(' + z + ')');\n" + "})();"; Object result = v8.executeScript(jsCode); System.out.println(result); }