Retrieve HTML element from webview on click

元气小坏坏 提交于 2021-02-11 09:44:19

问题


I'm facing an issue with Android's webview.

I'm trying to get the HTML Element from a webview (for example, a field to complete).

I don't have any hand on the displayed webview, I'm just a consummer.

I have try some answers from stack over flow (onTouchListener, injection of JS code, addJavascriptInterface,...), but nothing works. With the "hitTestResult", I'm only facing "null" when I click somewhere inside the webview (even if this is a field to complete).

Do you know how to retrieve the HTML element ?

Thanks you.

Edit: I have modified a lot my code, so for now, it looks like :

First, I bind my view :

binding = MyViewBinding.inflate(layoutInflater)

And I load my webview :

binding.webView.webViewClient = object: WebViewClient() {
    override fun shouldOverrideUrlLoading(
        view: WebView?,
        request: WebResourceRequest?
    ): Boolean {
        view?.loadUrl(request?.url.toString())
}
binding.webView.setOnTouchListener { view, event ->
    val hr = (view as WebView).hitTestResult
    Log.i("LOG", "getExtra = " + hr.extra + "Type= " + hr.type)
    false
}

I have also try : (inside "shouldOverrideUrlLoading", I have never see any toast)

view?.addJavascriptInterface(object : Any() {
    @JavascriptInterface
    @Throws(Exception::class)
    fun performClick() {
        Log.d("LOGIN::", "Clicked")
        Toast.makeText(this@MyActivity, "clicked", Toast.LENGTH_LONG).show()
    }
}, "test")

In the WebViewClient object (when I have done this, I've set javaScriptEnabled and domStorageEnabled to true), but no callback :

override fun onPageFinished(view: WebView?, url: String?) {
    super.onPageFinished(view, url)

    Log.d("TAG", "test tag")
    view?.evaluateJavascript(addMyClickCallBackJs(), null)
    view?.evaluateJavascript(test(), null)
}
@JavascriptInterface
fun onData(value: String?) {
    print("value")
}

@JavascriptInterface
fun myClick(idOrClass: String) {
    Log.d("TAG", "myClick-> $idOrClass")
}

fun addMyClickCallBackJs(): String? {
    var js = "javascript:"
    js += "function myClick(event){" +
    "if(event.target.className == null){my.myClick(event.target.id)}" +
    "else{my.myClick(event.target.className)}}"
    js += "document.addEventListener(\"click\",myClick,true);"
    return js
}

fun test(): String {
    return "javascript:(function(){"+
    "l=document.getElementById('*');"+
    "e=document.createEvent('HTMLEvents');"+
    "e.initEvent('click',true,true);"+
    "l.dispatchEvent(e);"+
    "})()"
}

来源:https://stackoverflow.com/questions/60623503/retrieve-html-element-from-webview-on-click

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!