addEventListener on HTML input not working within an Android WebView

Viewed 1797

I am loading the following page on an Android WebView: URL

This is an overview of the page loaded.

The page loaded on a WebView

I am trying to add a click listener on the RESET button. This button has no id but has a name='resetbutton', so I tried to get a reference to it using document.getElementsByName('resetbutton')[0], and as you can see on the screenshot above, it should work.

Thing is, when I attach an event listener to the input, it does not trigger. Here is my client code:

mWebview.settings.apply {
    javaScriptEnabled = true
    domStorageEnabled = true
}
WebView.setWebContentsDebuggingEnabled(true)
mWebview.webViewClient = object : WebViewClient() {
    override fun onPageFinished(view: WebView?, url: String?) {
        super.onPageFinished(view, url)
        mWebview.evaluateJavascript("javascript:document.getElementsByName('resetbutton')[0].addEventListener('click', function() {\n" +
            "   Android.onSubmit('CLICK', 'ED');});") {
            Toast.makeText(this@GuestBookActivity, "Got $it", Toast.LENGTH_LONG).show()
        }
    }
}
mWebview.addJavascriptInterface(GuestBookWebInterface(this), "Android")
mWebview.loadUrl("http://users4.smartgb.com/g/g.php?a=s&i=g44-71854-e8")

GuestBookWebInterface.kt

class GuestBookWebInterface(private val mContext: Context) {
    @JavascriptInterface
    fun onSubmit(name: String, message: String) {
        Log.i("webhook", "Name: $name, message: $message")
    }
}

I run the app, I hit the RESET button, but I can't see the webhook entry in the logs that I'm looking for. I tried to make a simple visible change on the page's body (like changing its background color) and it worked.

I thought maybe the event listener wasn't being attached for some reason. So next I tried this:

mWebview.evaluateJavascript("javascript:Android.onSubmit(document.getElementsByName('resetbutton')[0], 'ED');\n" +
                        "    document.getElementsByName('resetbutton')[0].addEventListener('click', function() {\n" +
                        "        Android.onSubmit('CLICK', 'ED');\n" +
                        "    });")

The point was to make sure that the reference to the input button wasn't undefined. My assumption was valid, the reference was undefined in deed. When I run the app now, I can see this log on the console:

webhook: Name: undefined, message: ED

My question is: what am I missing here ? How can I go about making this event listener trigger ?

0 Answers
Related