在字符串中有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对象但在回调中接收到一个字符串?