Is there a way if I can check status code for the url I load into a webview?
I want to check if the url has anymore redirects, and if not I want to execute a piece of code.
Iam implementing the WebViewClient and I want to execute a code in the onPageFinished();
EDIT: The url I load is a login screen. I want to check if the user has successfully logged in.
How can I achieve this?
webView.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.isEmpty()){
// do your stuff as you want.
}
return true;
}
public void onPageFinished(WebView view, String url) {
// do your stuff as you want
}
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
}
});
Use HttpURLConnection class.
URL url = new URL("http://example.com");
HttpURLConnection connection = (HttpURLConnection)url.openConnection();
connection.setRequestMethod("GET");
connection.connect();
int code = connection.getResponseCode();
There you have the http code returned.
Hope this helps.
Try this
public void evaluateJavascript (String script, ValueCallback<String> resultCallback)
Related
I am try to load URL which internally redirect another URL in android WebView, but it is showing blank page. I have checked and found that I am trying to load http://erp1.stmarysschoolbxr.org/StudentReportCard.aspx?card=admitcard&AdmNo=22L001 which indirect to another URL http://erp1.stmarysschoolbxr.org/ReportPage.aspx but it is showing blank page. But when I try to load it in browser, it is loading fine.
Below is my webview code
binding.webView.getSettings().setJavaScriptEnabled(true);
binding.webView.getSettings().setLoadWithOverviewMode(true);
binding.webView.getSettings().setUseWideViewPort(true);
binding.webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, final String url) {
hideLoader();
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
hideLoader();
}
});
binding.webView.loadUrl(url);
}
According to WebView doc:
Note: Do not call WebView#loadUrl(String) with the request's URL and then return true.
This unnecessarily cancels the current load and starts a new load with the same URL.
The correct way to continue loading a given URL is to simply return false,
without calling WebView#loadUrl(String).
just return false in shouldOverrideUrlLoading without callingview.loadUrl(url);
I am using a webview to submit a form and redirect. When the form is submitted successfully it will print a json response to the console.
My question is how can I get the jsonData String from the client?
chromium: [INFO:CONSOLE(1)] "Callback....jsonData, etc"
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Insert your code here
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
}
});
You could extend the WebViewClient class and create a method to intercept the POST request made from clicking the form post button in the HTML in your WebView. Then, make the HTTP POST request in the code, rather than in the WebView and parse the results anyway you wish, then refresh the WebView any way you wish at the end of it all. There is an example of doing so here:
https://github.com/KeejOow/android-post-webview/blob/master/PostWebview/postwebview/src/main/java/com/solidsoftware/postwebview/InterceptingWebViewClient.java
In my android app I am connecting to a secure site where my login credentials are contained in custom headers. I am able to log in successfully because the custom headers are sent with the new page request.
Based on my custom header information there is specific page functionality which is enabled for my device. The problem is that when I load resources from the home page after login the custom headers that I specify in the webview.LoadUrl(); are not sent. So the end result is that I can log in but do not receive the special functionality that is associated with my device.
I have tried both of these overrides. shouldOverrideUrlLoading seems to work when changing URL's but shouldInterceptRequest does not seem to get called on resource requests? If it is my implementation does not work?
#Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
request.getRequestHeaders().putAll(getExtraHeaders());
return super.shouldInterceptRequest(view, request);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url, getExtraHeaders());
return false;
}
See if this works a little better for you:
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.post(new Runnable() {
#Override
public void run() {
view.loadUrl(url, getExtraHeaders());
}
});
// true means: yes, we are overriding the loading of this url
return true;
}
This additional code is just a suggestion/outline and should not be taken as cut/paste ready code
#Override
public WebResourceResponse shouldInterceptRequest(WebView view, WebResourceRequest request) {
String mimetype;
String encoding;
Map<String, String> headers = new HashMap<>();
headers.putAll(request.getRequestHeaders());
headers.putAll(getExtraHeaders());
URL url = request.getUrl().toString();
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
for (String key : headers.keySet()) {
conn.setRequestProperty(k, headers.get(k));
// TODO look for the mimetype and encoding header information and set mimetype and encoding
}
return new WebResourceResponse(mimetype, encoding, conn.getInputStream());
// return null here if you decide to let the webview load the resource
}
Maybe try a different approach, store whatever your need in a cookie for your host using WebKit's CookieManager and use the request's cookie header instead of your custom headers
First i surfed the web but no answer was found matching my case.
I want to grab a specific redirect url from a webview and then keep the webview from opening it. The case is an Instagram redirect url after the user authorized my app. How to do it? Here is my code:
webView = (WebView) findViewById(R.id.webView1);
webView.getSettings().setJavaScriptEnabled(true);
webView.getSettings().setLoadWithOverviewMode(true);
webView.getSettings().setUseWideViewPort(true);
webView.getSettings().setBuiltInZoomControls(true);
webView.setWebViewClient(new WebViewClient());
webView.loadUrl("https://api.instagram.com/oauth/authorize/?client_id=my_client_id&redirect_uri=my_redirect_uri&response_type=code");
You will have to set your custom WebviewClient overriding shouldOverrideUrlLoading method for your webview before loading the url.
mWebView.setWebViewClient(new WebViewClient()
{
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url)
{
return shouldOverrideUrlLoading(url);
}
#TargetApi(Build.VERSION_CODES.N)
#Override
public boolean shouldOverrideUrlLoading(WebView webView, WebResourceRequest request)
{
Uri uri = request.getUrl();
return shouldOverrideUrlLoading(uri.toString());
}
private boolean shouldOverrideUrlLoading(final String url)
{
Log.i(TAG, "shouldOverrideUrlLoading() URL : " + url);
// Here put your code
return true; // Returning True means that application wants to leave the current WebView and handle the url itself, otherwise return false.
}
});
mWebView.loadUrl("Your URL");
Checkout the example code for handling redirect urls and open PDF without download, in webview.
https://gist.github.com/ashishdas09/014a408f9f37504eb2608d98abf49500
You should override shouldOverrideUrlLoading:
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView wView, String url) {
if (url.indexOf('api.instagram.com') > -1) //check if that's a url you want to load internally
{
webView.loadUrl(url);
return true;
}
else
{
return false; //Let the system handle it
}
}
});
Finally thanks to the answer given to my question by Udi I, with a little change, i managed to find a solution to the problem. Here is the code which worked for me:
webView.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView wView, String url) {
return (url.indexOf("some part of my redirect uri") > -1);
}
});
webView.loadUrl(myUrl); //myUrl is the initial url.
Using the above code, if there will be any url containing redirect uri, webView won't load it. Else, webView will load it. Also thanks to Kamil Kaminski.
Simply set WebViewClient for your WebView, and override shouldOverrideUrlLoading in WebViewClient. In that method you can grab your url, and decide whether or not your WebView should follow redirection url. Here's example:
webView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// here you can assign parameter "url" to some field in class
// return true if you want to block redirection, false otherwise
return true;
}
});
You can compare URL strings / particular word, and take actions accordingly -
public boolean shouldOverrideUrlLoading(WebView view, String url) {
super.shouldOverrideUrlLoading(view, url);
if (url.contains(".pdf")
openPDF(url); // handle pdf opening
if(url.startsWith("tel:")
callNumber(url); // handle call processing
...
}
Just to add more, you can prevent webview from showing traditional error message screens, or bypass known errors -
#Override
public void onReceivedError(WebView view, int errorCode,
String description, String failingUrl) {
if (errorCode == -10) {
System.out.println("Error occured: Error code: "
+ errorCode + "..Ignoring this error");
return;
}
else
{
// Show your custom screen to notify error has occured
}
...
}
In webview android I am trying to load a url and in order to check if the load of this url is done successfully (internet connection was available, the server was up etc) I was under the impression that webview.loadUrl would throw exceptions, but wrong! as it explicitly is stated in here "an exception will NOT be thrown".
So how can I check to see if webview.loadUrl did not fail ?
Unfortunately, currently there is no easy way in WebView to ensure that everything on the page has been loaded successfully. We are hoping for a better API to come up in future version. Let me explain what you can do now.
First of all, in order to detect any problems that prevent WebView from making a connection to the server for loading your main page (e.g. bad domain name, I/O error, etc.), you should use WebViewClient.onReceivedError callback as other people correctly suggest:
public class MyWebViewClient extends WebViewClient {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
// Make a note about the failed load.
}
}
myWebView.setWebViewClient(new MyWebViewClient());
If the server connection was successful, and the main page was retrieved and parsed, you will receive WebView.onPageFinished callback, so you also need to have this in your WebViewClient subclass:
public class MyWebViewClient extends WebViewClient {
...
#Override
public void onPageFinished(WebView view, String url) {
// Make a note that the page has finished loading.
}
...
}
The caveat here is that if you have received an HTTP error from the server (e.g. a 404 or a 500 error), this callback will be called anyway, it's just the content that you will get in your WebView will be a server error page. People suggest different ways of how to deal with it, see the answers here: How can I check from Android WebView if a page is a "404 page not found"? Basically, it really depends on what you expect to be a "good" page and a "error" page. Unfortunately, there is currently no way for the app to get the HTTP response code from WebView.
The callbacks WebViewClient.onPageStarted and WebViewClient.onProgressChanged are only useful if you want to draw a progress bar as you are loading the page.
Also note that the way of overriding WebViewClient.shouldOverrideUrlLoading that people usually suggest is not correct:
public class MyWebViewClient extends WebViewClient {
...
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// !!! DO NOT DO THIS UNCONDITIONALLY !!!
view.loadUrl(url);
return true;
}
...
}
What few developers realize is that the callback is also called for subframes with non-https schemes. If you'll encounter something like <iframe src='tel:1234'>, you will end up executing view.loadUrl('tel:1234') and your app will show an error page, since WebView doesn't know how to load a tel: URL.
It is recommended to simply return false from the method, if you want WebView to do the loading:
public class MyWebViewClient extends WebViewClient {
...
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Returning 'false' unconditionally is fine.
return false;
}
...
}
This doesn’t mean you should not call WebView.loadUrl from shouldOverrideUrlLoading at all. The specific pattern to avoid is doing so unconditionally for all URLs.
public class AppWebViewClient extends WebViewClient {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
// TODO Auto-generated method stub
super.onPageStarted(view, url, favicon);
setProgressBar(true);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
//Page load finished
super.onPageFinished(view, url);
setProgressBar(false);
}
}
and then you can do
webView.setWebViewClient(new AppWebViewClient());
For the error part you can override the onReceivedError method
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
// TODO Auto-generated method stub
super.onReceivedError(view, errorCode, description, failingUrl);
}
Here is what I came up with, it works like a charm.
Boolean failedLoading = false;
WebView webView = view.findViewById(R.id.webView);
webView.loadUrl("www.example.com");
webView.setWebViewClient(new WebViewClient() {
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (!failedLoading) {
webView.setVisibility(View.VISIBLE);
webView.setAlpha(0f);
ObjectAnimator anim = ObjectAnimator.ofFloat(webView, "alpha",1f);
anim.setDuration(500);
anim.start();
}
}
#Override
public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
super.onReceivedError(view, request, error);
failedLoading = true;
}
});
It will also work great if you add some kind of a refresh button and then you can call the code above inside a function to try again.
You can check if a URL is loaded successfully by using onProgressChanged()
mWebView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress) {
progressBar.setProgress(progress);
if (progress == 100) {
//your url is loaded successfully
}
}
});