0

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

4

1 回答 1

0

这篇文章可能会有所帮助:

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"}
    }
});

于 2020-07-17T16:09:11.647 回答