android, как объект json изменяется на строку в обратном вызове WebView.evaluateJavascript
С функцией js в строке:
val strFormat_elmLocation = "(function() { \n" +
"var elementId = '%s';\n" +
"try {\n" +
" var elm = document.getElementById(elementId);\n" +
" var width = window.innerWidth;\n" +
" var height = window.innerHeight;\n" +
"\n" +
" var rect = document.getElementById(elm.id).getBoundingClientRect();\n" +
"\n" +
// here it returns seems a json object,
// but in the evaluateJavascript's callback it receives a string,
// how does it work?
" return {\n" +
" 'elmId': elm.id,\n" +
" 'left': Math.floor(rect.left),\n" +
" 'top': Math.floor(rect.top),\n" +
" 'width': Math.floor(width),\n" +
" 'height': Math.floor(height)\n" +
" };\n" +
"} catch (e) {\n" +
"}\n" +
"return '';})()"
private fun doEvaluateJavascript(webview: WebView, elementId: String) {
val strJs = String.format(strFormat_elmLocation, elementId)
webview.evaluateJavascript(strJs) { data -> // data returned from javascript, here it is a string, not json object ??
if (!data.isNullOrBlank() && data.isNotEmpty()) {
try {
val obj: JSONObject = JSONObject(data)
val moduleId = obj.optString("elmId")
val left = obj.optInt("left")
val top = obj.optInt("top")
val htmlWindowWidth = obj.optInt("width")
val htmlWindowHeight = obj.optInt("height")
// do something
} catch (ex: Throwable) {
}
}
}
}
то evaluateJavascript
как показано ниже, а интерфейс обратного вызова принимает строку.
public void evaluateJavascript(String script, @Nullable ValueCallback<String> resultCallback) {
throw new RuntimeException("Stub!");
}
Как javascript возвращает объект json, но в обратном вызове получена строка?
1 ответ
Этот пост может помочь:
The main thing to note is that the String returned in OnReceiveValue is either a JSON Value, JSON Object or JSON Array depending on what you return.
Things to note about this is if you return a single value, you need to use setLenient(true) on a JSON reader for it to work.
а также
The method also handles Javascript objects:
webView1.evaluateJavascript("(function() { return { var1: \"variable1\", var2: \"variable2\" }; })();", new ValueCallback<String>() {
@Override
public void onReceiveValue(String s) {
Log.d("LogName", s); // Prints: {"var1":"variable1","var2":"variable2"}
}
});