How to block WebView in Android from converting 'https' to 'http'? - android

My WebView converts https to http, as evident from checking the url parameter in shouldOverrideUrlLoading() method.
I have tried using
webView.getSettings().setMixedContentMode(WebSettings.MIXED_CONTENT_COMPATIBILITY_MODE), but it doesn't work.
How do I fix this?
Please help!

you can handle every url as you wish just set up your webview via customized WebViewClient
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView webView, String url) {
if (url.startWith("https")) {
//do whatever you need
}
return false;
}else if(....

Related

How can I Block a Site in WebView

I have to make a webbrowser for android, so I want to try to block a site.
How can I do that?
Lets say your WebView id is myWebView then what you will do is this :
WebView wb = (WebView) findViewById(R.id.myWebView);
wb.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.contains("http://yourBlockedUrl.com")){
//notify the user that this url is blocked
return true;
}
return false;
}
});
by doing this you are overriding the url loading of your webview you can thus block a url from loading.
say you get the url sent as a string "www.google.com", from the edittext just do a check if this is a blocked url.
for example
if( "www.google.com".equalsIgnoreCase(blocked_string))
{
webview.setVisibility(View.GONE);
warning_view.setVisibilty(View.VISIBLE);
}
or you could try overriding the shouldOverrideUrlLoading() in the WebViewClient class
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
if(my_url.equals("www.google.com")){
//do something.
}
return true;
}
Creating and setting a WebViewClient subclass. It will be called when things happen that impact the rendering of the content, eg, errors or form submissions. You can also intercept URL loading here (via shouldOverrideUrlLoading()).
public void gotoUrl(View view) {
EditText theEditText = (EditText)findViewById(R.id.urlTxt);
theUrl = theEditText.getText().toString();
//
// String blok= "http://www.teknojurnal.com";
webBrowserKu.loadUrl(theUrl);
}
my web browser when klik go, will process this, so what is the problem? why I cant do the steps from anything for blocking one site?

WebView shouldOverrideUrlLoading() not called for invalid links

There are two types of links in the HTML file:
(1) A normal link like http://www.bbb.com/q?type=normal
(2) A short link like /q?type=short.
For the first kind, just load the url. For the second kind, I should prepend it with a fixed address like http://www.abc.com before loading the url.
I am trying to do this with overriding the shouldOverrideUrlLoading() function in WebViewClient. However this function doesn't gets called for the second type of link. I tried prepending the "http://www.abc.com" to the second type of links in the HTML file. Then the function does get called when I click the second kind of link.
I think what's happening is WebView will first check if the link is a valid url. Only if it is valid will the function gets called. Am I right? How can I solve this? Thanks in advance.
contentWebView = new WebView(context);
webViewClient = new WebViewClient() {
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// String not in Logger.
Log.d(TAG, "Here!");
Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
context.startActivity(intent);
return true;
}
#Override
public void onPageFinished(WebView view, String url) {
super.onPageFinished(view, url);
if (hosted) {
contentWebView.setVisibility(VISIBLE);
} else {
summaryTextView.setVisibility(VISIBLE);
articleLinkButton.setVisibility(VISIBLE);
}
progressBar.setVisibility(View.GONE);
}
};
contentWebView.setWebViewClient(webViewClient);
contentWebView.getSettings().setJavaScriptEnabled(true);
contentWebView.loadData(fullString, "text/html", "utf-8");
contentWebView.setVisibility(GONE);
More on this:
I tried changing
contentWebView.loadData(fullString, "text/html", "utf-8");
to
contentWebView.loadDataWithBaseURL("http://www.abc.com", fullString, "text/html", "utf-8", null);
Then the function gets called.
If I change the short link to a full link in the html string manually. Then the function also gets called.
So I think this is probably what is happening: The WebView checks if the link URL is valid. Only when the URL is valid will the shouldOverrideUrlLoading() be called.
You're probably using the KitKat WebView. This is a known issue (I think it's outlined in the migration guide) where URLs that can't be resolved against the base URL are dropped on the floor (you won't get any callbacks for them, neither shouldOverrideUrlLoading nor onPageStarted).
The problem is that your base URL is a data url, so you're trying to resolve '/q?type=short' against 'data:text/html,...' which doesn't make much sense and so the whole attempt to navigate to the URL gets ignored.
This was different for the pre-KK WebView which used KURL instead of GURL for URL processing. GURL is generally more strict (and more secure) than KURL, which is the cause for some incompatibility between the two WebView versions.
Maybe try using onPageStarted method
solution that worked for me was to use loadDataWithBaseURL with an invalid baseUrl and detect that and remove it and replace with "http://" during setWebViewClient
public class MyActivity
extends Activity
{
private static final String badurl = "http://myappname.invalid/";
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
...
WebView wv = ((WebView)findViewById(R.id.webview));
WebSettings settings = wv.getSettings();
settings.setJavaScriptEnabled(false);
settings.setSupportMultipleWindows(true);
wv.setWebChromeClient(new WebChromeClient() {
#Override
public boolean onCreateWindow(WebView view, boolean isDialog, boolean isUserGesture, Message resultMsg)
{
handleUrlview.getHitTestResult().getExtra());
return true;
}
});
wv.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
handleUrl(url);
return true;
}
});
wv.loadDataWithBaseURL(badurl,text,"text/html","utf-8",null);
}
private void handleUrl(String url)
{
if (url.startsWith(badurl))
url = "http://"+url.substring(badurl.length());
try {
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
} catch (ActivityNotFoundException e) { }
}
}
i faced this problem too and solved it by replacing my html response. In my html response there is no any host in "href" html tags. Then i replaced it following codes and thats working like a charm now :)
String htmlString = AppCache.homePageResponse.showcaase.replace("href=\"/", "href=\"" + "evidea://" );
I found that if your page runs in an iframe, clicking on external (http://www...) links does NOT trigger shouldOverrideUrlLoading() !
See shouldOverrideUrlLoading() not called for external links from iframe
Try this
private static WebView webView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main); //should be activity_main
webView = (WebView) findViewById(R.id.web);
webView.setWebViewClient(new webviewclient());
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("http://www.yahoo.com");
}
public class webviewclient extends WebViewClient{
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(request.toString());
return true;
}

Android WebView navigation

I want to add news and weather app in webview. But jumping to anyther website from webview is not an option. How can I restrict a webview for a certain website.
Thanks.
Create your own WebViewClient:
public class CustomWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if(url.getHost().equals("weather.com")){
// load link
return false;
}else{
// block link
return true;
}
}
}
Use it like this:
webview.setWebViewClient(new CustomWebViewClient());
EDIT Note:
an example of a getHost() function
If I understand the question correctly you might want to implement your own WebViewClient. That will allow you to handle the page navigation. Check out the link for a tutorial from Google.
viewer.setWebViewClient(new WebViewClient(){
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
//Block all URL accesses.
return false;
}
});
That should prevent access to anything. You need to handle specific URL's in this function if you want to allow them.

Android WebView, how to handle redirects in app instead of opening a browser

So right now in my app the URL I'm accessing has a redirect, and when this happens the WebView will open a new browser, instead of staying in my app. Is there a way I can change the settings so the View will redirect to the URL like normal, but stay in my app instead of opening a new browser?
Edit:
I want the redirecting URL, I just don't know how to create it, so the only way to get to that URL is through one that will cause a redirect to the one I want.
For example: When you go here: http://www.amazon.com/gp/aw/s/ref=is_box_/k=9780735622777 notice how it will redirect the URL to the actual product. In my app, if I open it in a new browser, it will do that just fine, however if I keep it in my app with a WebView, it will show up as though it's doing a search for k=9780735622777, like this: http://www.amazon.com/gp/aw/s/ref=is_s_?k=k%3D9780735622777&x=0&y=0 . OR, it will open the view in the browser and show what is appropriate. However, I want to keep everything in my app.
Create a WebViewClient, and override the shouldOverrideUrlLoading method.
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url){
// do your handling codes here, which url is the requested url
// probably you need to open that url rather than redirect:
view.loadUrl(url);
return false; // then it is not handled by default action
}
});
According to the official documentation, a click on any link in WebView launches an application that handles URLs, which by default is a browser. You need to override the default behavior like this
myWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
Just adding a default custom WebViewClient will do. This makes the WebView handle any loaded urls itself.
mWebView.setWebViewClient(new WebViewClient());
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.
}
});
Checkout the example code for handling redirect urls and open PDF without download, in webview.
https://gist.github.com/ashishdas09/014a408f9f37504eb2608d98abf49500
Create a class that implements webviewclient and add the following code that allows ovveriding the url string as shown below.
You can see these [example][1]
public class myWebClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
On your constructor, create a webview object as shown below.
web = new WebView(this); web.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.FILL_PARENT));
Then add the following code to perform loading of urls inside your app
WebSettings settings=web.getSettings();
settings.setJavaScriptEnabled(true);
web.loadUrl("http://www.facebook.com");
web.setWebViewClient(new myWebClient());
web.setWebChromeClient(new WebChromeClient() {
//
//
}
Please use the below kotlin code
webview.setWebViewClient(object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, url: String): Boolean {
view.loadUrl(url)
return false
}
})
For more info click here
In Kotlin, to navigate within same webView we needed to override the shouldOverrideUrlLoading for webview
If return type is true then navigation will be blocked If return
type is false then navigation will happen
object : WebViewClient() {
override fun shouldOverrideUrlLoading(view: WebView, request: WebResourceRequest): Boolean {
return true
}
}.also { webView.webViewClient = it }
#Override
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
if (url.equals("your url")) {
Intent intent = new Intent(view.getContext(), TransferAllDoneActivity.class);
startActivity(intent);
}
}

Clicking URLs opens default browser

I have loaded an external URL in my WebView. Now what I need is that when the user clicks on the links on the page loaded, it has to work like a normal browser and open the link in the same WebView. But it's opening the default browser and loading the page there?
I have enabled JavaScript. But still it's not working. Have I forgotten something?
If you're using a WebView you'll have to intercept the clicks yourself if you don't want the default Android behaviour.
You can monitor events in a WebView using a WebViewClient. The method you want is shouldOverrideUrlLoading(). This allows you to perform your own action when a particular URL is selected.
You set the WebViewClient of your WebView using the setWebViewClient() method.
If you look at the WebView sample in the SDK there's an example which does just what you want. It's as simple as:
private class HelloWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
}
in some cases you might need an override of onLoadResource if you get a redirect which doesn't trigger the url loading method. in this case i tried the following:
#Override
public void onLoadResource(WebView view, String url)
{
if (url.equals("http://redirectexample.com"))
{
//do your own thing here
}
else
{
super.onLoadResource(view, url);
}
}
Official documentation says, click on a link in a WebView will launch application that handles URLs. You need to override this default behavior
myWebView.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
return false;
}
});
or if there is no conditional logic in the method simply do this
myWebView.setWebViewClient(new WebViewClient());
Add this 2 lines in your code -
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.setWebViewClient(new WebViewClient());
The method boolean shouldOverrideUrlLoading(WebView view, String url) was deprecated in API 24. If you are supporting new devices you should use boolean shouldOverrideUrlLoading (WebView view, WebResourceRequest request).
You can use both by doing something like this:
if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
newsItem.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {
view.loadUrl(request.getUrl().toString());
return true;
}
});
} else {
newsItem.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
});
}
Arulx Z's answer was exactly what I was looking for.
I'm writing an app with Navigation Drawer with recyclerview and webviews, for keeping the web browsing inside the app regardless of hyperlinks clicked (thus not launching the external web browser). For that it will suffice to put the following 2 lines of code:
mWebView.setWebChromeClient(new WebChromeClient());
mWebView.setWebViewClient(new WebViewClient());
exactly under your WebView statement.
Here's a example of my implemented WebView code:
public class WebView1 extends AppCompatActivity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
WebView wv = (WebView) findViewById(R.id.wv1); //webview statement
wv.setWebViewClient(new WebViewClient()); //the lines of code added
wv.setWebChromeClient(new WebChromeClient()); //same as above
wv.loadUrl("http://www.google.com");
}}
this way, every link clicked in the website will load inside your WebView.
(Using Android Studio 1.2.2 with all SDK's updated)

Categories

Resources