How does evaluateJavascript work?

后端 未结 6 829
执念已碎
执念已碎 2020-11-27 03:06

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\         


        
6条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-27 03:24

    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
    }
    

提交回复
热议问题