[英]how to call javascript functions that call another javascript function in Android webview
If jsCode is: 如果jsCode为:
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 运行JavaScript代码并在Java中获取“ test”作为值返回
But what if I need more complex javascript code, for example: 但是,如果我需要更复杂的javascript代码,例如:
function() {
return test();
}
function test() {
return "test";
}
, which defines a function test() and calls it; ,它定义了一个函数test()并对其进行调用;
Passing this javascript code to webview's evaluateJavascript gives error: "Uncaught SyntaxError: Unexpected token function", source: (1) 将此JavaScript代码传递给webview的validateJavascript会产生错误:“未捕获的SyntaxError:意外的令牌函数”,来源:(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 这些包装容器称为立即调用的函数表达式
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.