首页 > 解决方案 > 有没有办法从 android studio 中的 webView 获取元素?

问题描述

我试图在 id="mode" 时获取我的 h1 的值,但它只返回I/chromium: [INFO:CONSOLE(1)] "Uncaught TypeError: Cannot read property 'innerHTML' of null", source: about:blank (1)。当我尝试直接在 webView 中加载 html 字符串时,它工作正常。也许您知道执行此操作的正确方法。

fun getMode(ip: String): String {
    var mode = ""

    wvDevice[0].settings.javaScriptEnabled = true
    wvDevice[0].settings.domStorageEnabled = true
    wvDevice[0].settings.databaseEnabled = true



    wvDevice[0].webViewClient = object : WebViewClient() {
        override fun onPageFinished(view: WebView, url: String) {
            view.evaluateJavascript("document.getElementById('mode').innerHTML")
            { value ->
                val splitted = value.split("\"")
                for (i in splitted.indices){
                    if (splitted[i] == "RGB" || splitted[i] == "TW"){
                        mode = splitted[i]
                        println("mode: $mode")
                    }
                }
            }

        }
    }

    /*wvDevice[0].loadData("<html><head><meta name=\"viewport\" content=\"width=device-width, initial-scale=1\">\n" +
            "<link rel=\"icon\" href=\"data:,\">\n" +
            "<link rel=\"stylesheet\" href=\"https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css\">\n" +
            "<script src=\"https://cdnjs.cloudflare.com/ajax/libs/jscolor/2.0.4/jscolor.min.js\"></script>\n" +
            "</head><body><div class=\"container\"><div class=\"row\"><h1 id=\"mode\">TW</h1><h2>533</h2></div>\n" +
            "<a class=\"btn btn-primary btn-lg\" href=\"%23\" id=\"change_color\" role=\"button\">Change Color</a> \n" +
            "<input class=\"jscolor {onFineChange:'update(this)'}\" id=\"rgb\" autocomplete=\"off\" style=\"background-image: none; background-color: rgb(255, 255, 255); color: rgb(0, 0, 0);\"></div>\n" +
            "<script>function update(picker) {document.getElementById('rgb').innerHTML = Math.round(picker.rgb[0]) + ', ' +  Math.round(picker.rgb[1]) + ', ' + Math.round(picker.rgb[2]);\n" +
            "document.getElementById(\"change_color\").href=\"?r\" + Math.round(picker.rgb[0]) + \"g\" +  Math.round(picker.rgb[1]) + \"b\" + Math.round(picker.rgb[2]) + \"&\";}</script>\n" +
            "\n" +
            "</body></html>", "text/html; charset=utf-8", "UTF-8")*/
    wvDevice[0].loadUrl(ip)


    return mode

}

标签: androidkotlingetelementbyid

解决方案


尝试直接评估它,而不是将其包装到函数中。使用您当前的代码,您没有执行该功能。

wvDevice.evalueateJavascript("document.getElementById('mode')", object : ValueCallback<String>() {
    override fun onReceiveValue(value: String) {
        println(value)
    }
});

推荐阅读