Handling HTML onClick function on Webview. shouldOverrideUrlLoading() not called

Issue

I want to intercept an ‘onclick’ function from an HTML page loaded into my WebView.

<div class'button' onclick"location.href'http://do_something';">
<span>
  Click Here
</span></div>

this is the click event on HTML page that I’m interested, but unfortunately my WebClient’s ‘shouldOverrideUrlLoading()’ method not at all triggered for this click.

When I change the above HTML button like this(below) its work fine.

<a href"http://do_something">Click Here</a>

But I really don’t want to make any changes to HTML. Any idea to handle this click event without modifying the HTML contents?

Solution

Since the onclick attribute executes JavaScript (location.href), you need to enable JavaScript in your WebView:

val myWebView: WebView  findViewById(R.id.webview)
myWebView.settings.javaScriptEnabled  true

Note that this should be used carefully as it can introduce XSS vulnerabilities into your application.

Answered By – Marek

Leave a Comment