How to detect clicks on links in webview - java

I use this code to check if a user touched inside a webview
webview.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View v, MotionEvent event)
{
if(event.getAction() == MotionEvent.ACTION_UP)
{
//action
}
return false;
}
});
but I will need to do action only if user clicked (touched ) a link only ,not if the the user touch some pictures or do a scrool in webview.
I need to reinit some variables when new webpage is loaded ,or when a user clicks on a link , but not when he click random on screen or he do scrool.
i can not use
public void onPageStarted(WebView view, String url, Bitmap favicon)
or
public boolean shouldOverrideUrlLoading(WebView view, String url)
cause this are called multiple times while a page is loaded and I only need to do action first time only 1 time , when user click on a link (or button or something that make webview to load a new page)
Does anybody knwo how to do this?
Thank you in advance

first step - enable JavaScript:
WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
second step - create interface between Java and Javascript:
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 showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
register your interface:
webView.addJavascriptInterface(new WebAppInterface(this), "Android");
and put this JS in your html page:
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
example for html:
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
if pages which you are showing are not your you might download them as plain text, then insert JS and load html with myWebView.loadDataWithBaseURL. this way you have full control of which user is clicking and what to do with it
to be honest I don't understand why you cannot do this with shouldOverrideUrlLoading(WebView view, String url) by checking what is arriving in url String and setting 'consumed' flag or smth like this
also: whole code is stolen from HERE

Related

How can I open multiple PDF Links in Android WebView in Android?

I'm building android app where, I placed links to the page in webview on which multiple links are there pointing to PDFs. Everyday, new links are updated. I want to make such functionality that when user clicks on the particular PDF link, it should get opened in default PDF viewer or there itself.
Right now, nothing is happening when user clicks on PDF link within webview.
WebView w=(WebView)findViewById(R.id.web1);
WebSettings webSettings=w.getSettings();
webSettings.setDomStorageEnabled(true);
webSettings.setJavaScriptCanOpenWindowsAutomatically(true);
w.setWebViewClient(new WebViewClient());
w.loadUrl("http://collegecirculars.unipune.ac.in/sites/examdocs/_layouts/mobile/view.aspx?List=7ed6607e-6c43-401a-a922-bf8d8bf08ed8&View=dc261157-c533-4a60-977b-506fd87b2a19");
You can use Google Docs Viewer to read your pdf online:
WebView webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
String pdf = "http://collegecirculars.unipune.ac.in/sites/examdocs/Examiantions%20Timetables/Master-In-ARTS(M.A)(Rev.2008)-(24908)_Spl4-8-16.pdf?Mobile=1&Source=%2Fsites%2Fexamdocs%2F_layouts%2Fmobile%2Fview%2Easpx%3FList%3D7ed6607e%252D6c43%252D401a%252Da922%252Dbf8d8bf08ed8%26View%3Ddc261157%252Dc533%252D4a60%252D977b%252D506fd87b2a19%26ViewMode%3DSimple%26CurrentPage%3D1";
webview.loadUrl("http://drive.google.com/viewerng/viewer?embedded=true&url=" + pdf);
open in browser
Intent browserIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(pdf_url));
startActivity(browserIntent);
To override current URL :
private class MyWebViewClient extends WebViewClient {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url){
// here you can check PDF
url = url.toLowerCase();
view.loadUrl(url);
return true;
}
}
set this MyWebViewClient to your webView.
PaymentWebViewClient paymentWebViewClient = new PaymentWebViewClient();
webView.setWebViewClient(paymentWebViewClient);

Trouble with inserting JavaScript statement

I am currently creating an android application.
The aim of the application is to fire off some injected JavaScript code into the WebView that I have created within my android application. The problem that I am having is that the action that has been injected doesn't work.
You should also be aware that the html page that I am loading has been created locally. aim of the application is to have a toast message display.The code listing is below:
//uses javascript that is in the local HTML file
public class MainActivity extends Activity {
final String URL = "file:///android_asset/index.html";
private WebView myWebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
String test= "test";
String javascript ="javascript:document.addEventListener('click', function(){Android.showToast(toast)})";
myWebView.loadUrl(javascript);
myWebView.loadUrl(URL);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
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 showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
}
There are several issues with your implementation.
The toast variable might not be defined in the scope of your callback. Also, you are missing two semicolons, one right after calling the showToast method, and the other one at the end of the addEventListener method which results in a syntax error.
Finally, you are loading the Javascript code before loading the page, which gets it invalidated. You should be injecting your javascript code after the webpage has finished loading such as in the below example.
I've taken your example and rewrote it in a custom app to make sure it was working. Here's what I've written :
Android :
// Registering the JS interface
mWebView.addJavascriptInterface(new JSInterface(), "JSInterface");
// Waiting for the page to be fully loaded, and injecting the JS code
mWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
#Override
public void onPageFinished(WebView view, String url) {
view.loadUrl(INJECTED_CODE);
}
});
// Load your custom url
mWebView.loadUrl(YOUR_ACTUAL_URL);
/**
* Interface between Java and Javascript.
*/
public class JSInterface {
#JavascriptInterface
public void showToast(String toast) {
Log.d("debug", "I got : " + toast);
}
}
Injected javascript :
public static final String INJECTED_CODE = "javascript:"
+ "(function() { "
+ "document.addEventListener('click', function(){JSInterface.showToast('Hello Android !');});"
+ "})()";
You are attempting to call that JS code before loading your html page.
I would guess that the document object is not ready.
Change your event listener and bind to the window
From:
String javascript ="javascript:document.addEventListener('click', function(){Android.showToast(toast)})";
To:
String javascript ="javascript:window.addEventListener('click', function(){Android.showToast(toast)})";
And you should get a result. If not what is logcat spitting out when you click?
EDIT: Just saw Halim Qarroums onPageFinished solution, that is probably a better one in your case.

Invoke click through code in Webview

my name is Dan and I am trying to invoke a click on a HTML element through code in my Android application. If I try to click it through pure Javascript the result won't be the same as it is when the user clicks it.
So, how to press elements from a Webview component through Java code? Thanks in advance.
wv.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String link) {
return super.shouldOverrideUrlLoading(view, url);
}
});

Toast does not work in webview

Here is my code, this is literally step by step from developer.android.com
and it just doesn't work, no matter how many times I run it.
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView myWebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings = myWebView.getSettings();
webSettings.setJavaScriptEnabled(true);
myWebView.addJavascriptInterface(new WebAppInterface(this), "Android");
myWebView.loadUrl("http://www.google.com");
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
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 showToast(String toast) {
Toast.makeText(mContext, toast, Toast.LENGTH_SHORT).show();
}
}
}
When I run my app, the webpage will load, toast never shows.
I just can't seem to find the problem. Can someone tell me if this works for them?
EDIT: Here is some more that I'm confused about. Right after this, the instructions are
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 creates a toast message using the new interface when the user
clicks a button:
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
I have no idea where that part of js code goes either..
I have no idea where that part of js code goes either..
Create an html page in your assets folder, let's say named myWonderfulWebPage.html.
Copy the following HTML code to it :
<input type="button" value="Say hello" onClick="showAndroidToast('Hello Android!')" />
<script type="text/javascript">
function showAndroidToast(toast) {
Android.showToast(toast);
}
</script>
As you can see, when you'll click the button, the function showAndroidToast will be called and this function will call the one you defined in your Java code.
Now go back in your activity and load this page into your webview :
myWebView.loadUrl("file:///android_asset/myWonderfulWebPage.html");
Now you will see that it shows a blank page, with a button. Click it and it will show you the Toast on your webpage.
If the code you show is what is actually used then of course it will not work.
myWebView.loadUrl("http://www.google.com");
Google.com does not invoke the JS function you have added a bridge to. You need to use your own webpage that does indeed invoke the function, either local or on the web.-.-

webview never call ShuldOverrideUrlloading in webviewclient in android

I have a webview and a link on the URL that I have loaded on that webview, I want such like that if user clicks in this link the app will go to the background and open that link with the default web browser of that device. To do this I have done the following:
web = (WebView) findViewById(R.id.webview01);
progressBar = (ProgressBar) findViewById(R.id.progressBar1);
web.getSettings().setUseWideViewPort(true);
web.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
web.getSettings().setPluginState(PluginState.ON);
web.getSettings().setJavaScriptEnabled(true);
web.getSettings().setDomStorageEnabled(true);
web.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null
&& url.startsWith("http://the6figuremarketer.com/apps/androidfb21/thks.html")) {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
} else {
return false;
}
}
});
web.loadUrl("http://the6figuremarketer.com/apps/androidfb21/index.html");
but I figured out that the shouldoverrideurl method is nevet get called. what should I do now? can anyone help?
Look at shouldOverrideUrlLoading in WebView for Android not running.
shouldOverrideUrlLoading() is not called when you call loadurl on webview. It is called only when you click on a link in webview.

Categories