Ollie C
Ollie C

Reputation: 28519

Catch Javascript onclick events in an HTML page hosted in a WebView

Given an HTML document like this, hosted inside a WebView, how do I catch click events so they can be handled by my code, rather than the WebView?

<div onclick="location.href='http://www.blah.com/blah';">

The HTML is provided from another source, so it is desirable to to handle click events on the HTML without altering the HTML document as I cannot make assumptions about its structure.

Upvotes: 3

Views: 6782

Answers (2)

Daniel
Daniel

Reputation: 1012

You need to add a JavaScript interface (addJavascriptInterface) to your Webview and you can then call Java objects from your javascript code.

Check this:

http://developer.android.com/reference/android/webkit/WebView.html#addJavascriptInterface(java.lang.Object, java.lang.String)

You then create a function that is called on click, calling your registered Java object.

Upvotes: 1

R.daneel.olivaw
R.daneel.olivaw

Reputation: 2679

You can use the addJavaScriptInterfaceMethod() in WebView.

Also more information can be found here in the Binding JavaScript code to Android code section.

Upvotes: 4

Related Questions