0

If jsCode is:

function() {
   return "test"
}

I can do:

String js = "(" + jsCode + ") ();"
mWebView.evaluateJavascript(js, new ValueCallback<String>() {
    @Override
    public void onReceiveValue(String s) {
        Log.d("return value: ", s); // Returns the value from the function
    }
});

to run the javascript code and get "test" as a value back in Java

But what if I need more complex javascript code, for example:

function() {
   return test();
}

function test() {
    return "test";
}

, which defines a function test() and calls it;

Passing this javascript code to webview's evaluateJavascript gives error: "Uncaught SyntaxError: Unexpected token function", source: (1)

1 Answer 1

1

The reason for this problem is that this syntax is invalid:

(function() {
    return test();
}

function test() {
    return "test";
})();

This is because the wrapping brackets attempts to run the internal code as a single function, which hopefully you can see is clearly not a single function. Instead you need to treat the outer function like a container that internalises other functions and variables you need. For example, this should work:

(function(){

    function test(){
        return 'hello';
    }

    return test();
})();

These wrapping containers are called Immediately invoked function expressions

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.