How to Get Onclick Event on Webview in Android

How can I get onclick event on webview in android?

I took a look at this and I found that a WebView doesn't seem to send click events to an OnClickListener. If anyone out there can prove me wrong or tell me why then I'd be interested to hear it.

What I did find is that a WebView will send touch events to an OnTouchListener. It does have its own onTouchEvent method but I only ever seemed to get MotionEvent.ACTION_MOVE using that method.

So given that we can get events on a registered touch event listener, the only problem that remains is how to circumvent whatever action you want to perform for a touch when the user clicks a URL.

This can be achieved with some fancy Handler footwork by sending a delayed message for the touch and then removing those touch messages if the touch was caused by the user clicking a URL.

Here's an example:

public class WebViewClicker extends Activity implements OnTouchListener, Handler.Callback {

private static final int CLICK_ON_WEBVIEW = 1;
private static final int CLICK_ON_URL = 2;

private final Handler handler = new Handler(this);

private WebView webView;
private WebViewClient client;

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.web_view_clicker);

webView = (WebView)findViewById(R.id.web);
webView.setOnTouchListener(this);

client = new WebViewClient(){
@Override public boolean shouldOverrideUrlLoading(WebView view, String url) {
handler.sendEmptyMessage(CLICK_ON_URL);
return false;
}
};

webView.setWebViewClient(client);
webView.setVerticalScrollBarEnabled(false);
webView.loadUrl("http://www.example.com");
}

@Override
public boolean onTouch(View v, MotionEvent event) {
if (v.getId() == R.id.web && event.getAction() == MotionEvent.ACTION_DOWN){
handler.sendEmptyMessageDelayed(CLICK_ON_WEBVIEW, 500);
}
return false;
}

@Override
public boolean handleMessage(Message msg) {
if (msg.what == CLICK_ON_URL){
handler.removeMessages(CLICK_ON_WEBVIEW);
return true;
}
if (msg.what == CLICK_ON_WEBVIEW){
Toast.makeText(this, "WebView clicked", Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
}


Set an onClick listerner for a button inside a WebView in Android

All the above answers were good workarounds, however, I ended up using this solution and followed the guide on Android Developers page to enable JavaScript Binding. Note that Android interface needs to be used in the JavaScript file in order for the interception to work.

How to handle webview click event in android studio?

Binding JavaScript code to Android code

When developing a web application that's designed specifically for the WebView in your Android application, you can create interfaces between your JavaScript code and client-side Android code. For example, your JavaScript code can call a method in your Android code to start activity.

To bind a new interface between your JavaScript and Android code, call addJavascriptInterface(), passing it a class instance to bind to your JavaScript and an interface name that your JavaScript can call to access the class.

Caution: If you've set your targetSdkVersion to 17 or higher, you must add the @JavascriptInterface annotation to any method that you want available to your JavaScript (the method must also be public). If you do not provide the annotation, the method is not accessible by your web page when running on Android 4.2 or higher.

public class TableWebView extends Activity {

private SharedPreferences sharedPreferences;
private String customer_id,hotel_id;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_table_web_view);

WebView wvtable= (WebView)findViewById(R.id.webViewTable);

wvtable.setWebViewClient(new MyViewClient());

wvtable.addJavascriptInterface(new WebAppInterface(this), "Android");

WebSettings webSettings = wvtable.getSettings();

webSettings.setJavaScriptEnabled(true);

sharedPreferences = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
customer_id = sharedPreferences.getString("cust_id", "0");//if no customerid found automatically 0 will be used
hotel_id=sharedPreferences.getString("hotel_master_id","0");

wvtable.loadUrl("http://192.168.100.169/zoilo_admin/public/index.php/show-hotel-view?hotel_id="+hotel_id+"&customer_id="+customer_id+"&date_time="+ Util.selected_date_time);
}



public class WebAppInterface {
Context mContext;

/** Instantiate the interface and set the context */
WebAppInterface(Context c) {
mContext = c;
}

/** Show a toast from the web page */
@JavascriptInterface
public void startNewActivity() {
//startActivity(new Intent(this, youactivityname.class));
}
}

This creates an interface called Android for JavaScript running in the WebView. At this point, your web application has access to the WebAppInterface class. For example, here's some HTML and JavaScript that call your "startNewActivity" method of your class using the new interface when the user clicks a button:

<input type="button" value="Click Here" onClick="showActivity()" />

<script type="text/javascript">
function showActivity() {
Android.startNewActivity();
}
</script>

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

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.

Injecting JavaScript onclick() event inside WebView

Finally I found the answer...

webView.loadUrl("javascript:(function(){document.getElementById('buttonClick').click();})()");

here is the complete source code

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

public class Huddle extends Activity {
private WebView wv;
EditText editText;
TextView textView;
Button button,buttonClick;

@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);

setContentView(R.layout.main);

editText = (EditText)findViewById(R.id.titlebar);
textView = (TextView)findViewById(R.id.txt_html);
button = (Button)findViewById(R.id.button);
buttonClick = (Button)findViewById(R.id.buttonClick);

wv = (WebView) findViewById(R.id.webview);

wv.getSettings().setJavaScriptEnabled(true);
wv.getSettings().setUserAgentString("Mozilla/4.0 (compatible; MSIE 5.01; Windows NT 5.0)");
wv.addJavascriptInterface(new MyJavaScriptInterface(), "HTMLOUT");

wv.setWebChromeClient(new MyChromeClient());
wv.loadUrl("file:///android_asset/www/index.html");
wv.requestFocus();

button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
String txt = editText.getText().toString();
wv.loadUrl("javascript:sayHelloFromJS('"+txt+"')");
}
});
buttonClick.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {

wv.loadUrl("javascript:(function(){document.getElementById('buttonClick').click();})()");
}
});
}

class MyJavaScriptInterface
{
@SuppressWarnings("unused")
public void showHTML(final String html)
{
runOnUiThread(new Runnable() {
@Override
public void run() {
Huddle.this.textView.setText(html);
}
});
}
}

class MyChromeClient extends WebChromeClient{
}

class MyWebClient extends WebViewClient {
@Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);

}
}
}

index.html

add this index.html to assets\www\index.html

<html>
<script language="JavaScript">
function sayHelloFromJS(value) {
document.getElementById("namefromAndroid").value = value;
}

function setHtml(){
var HTML = ""+document.getElementById("namefromjs").value;
window.HTMLOUT.showHTML(HTML);
}

function doAlert() {
alert("JavaScript says: Hello Android !!! How are you?");

}
</script>
</head>
<body>
<p> Enter your name here <input type="text" id="namefromjs" />
<p> <input type="button" onclick= "setHtml()" value="Set Name in Android">
<p> Name from Android is <input type="text" id="namefromAndroid" />

<p> Button Click <input type="button" value="Click me" id="buttonClick" onclick= "doAlert()" />
</body>
</html>

res\layouts\main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>

<TextView
android:layout_width="184dp"
android:layout_height="22dp"
android:id="@+id/txt_html" android:layout_gravity="left|center_vertical"/>
<EditText
android:layout_width="161dp"
android:layout_height="wrap_content"
android:id="@+id/titlebar" android:layout_gravity="left|center_vertical"/>
<Button
android:layout_width="129dp"
android:layout_height="wrap_content"
android:text="Add text to web"
android:id="@+id/button"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Click Event"
android:id="@+id/buttonClick" android:layout_gravity="left|center_vertical"/>
<WebView android:id="@+id/webview" android:layout_width="match_parent"
android:layout_height="match_parent"/>
</LinearLayout>


Related Topics



Leave a reply



Submit