jiawen jiawen - 2 months ago 5
Android Question

how to call javascript functions that call another javascript function in Android webview

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)

Answer

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

Comments