有没有办法从android studio中的webView中获取ElementById?

问题描述 投票:1回答:1

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

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 ->

                value.forEach {
                    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
android kotlin getelementbyid
1个回答
0
投票

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

wvDevice.evalueateJavascript("document.getElementById('mode')", object : ValueCallback<String>() {
    override fun onReceiveValue(value: String) {
        println(value)
    }
});
© www.soinside.com 2019 - 2024. All rights reserved.