I\'m trying to use the new evaluateJavascript method in Android 4.4, but all I ever get back is a null result:
webView1.evaluateJavascript(\"return \\\"test\
To summarize the answer of @GauntFace and provide an alternative solution without using JSON parser:
If your JS function returns just a String
and you're wondering about why the string is mangled in Java, it's because it's JSON-escaped.
mWebView.evaluateJavascript("(function() { return 'Earvin \"Magic\" Johnson'; })();", new ValueCallback() {
@Override
public void onReceiveValue(String s) {
Log.d("LogName", s);
// expected: s == Earvin "Magic" Johnson
// actual: s == "Earvin \"Magic\" Johnson"
}
});
(note that onReceiveValue
always provides a String
while JS function may return a null
, a Number literal etc.)
To get the string value the same as in JS, if you're 100% sure you're expecting a proper String
returned, you'd need to JSON-unescape it, for example like that:
String unescaped = s.substring(1, s.length() - 1) // remove wrapping quotes
.replace("\\\\", "\\") // unescape \\ -> \
.replace("\\\"", "\""); // unescape \" -> "
However, note that s
might be a string "null"
if JS returns proper null
, so you obviously need to check that as the very first step.
if ("null".equals(s)) {
...
} else {
// unescape JSON
}