Open external WebView links in browser - android

I know this has been asked multiple times but I went through all the answers and I just cant get it to work. Im trying to make a simple webview app that handles external links in native browser.
package com.example.app;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends AppCompatActivity {
private WebView webview;
private long backPressedTime;
#Override
public void onBackPressed() {
if (webview.canGoBack()) {
webview.goBack();
} else {
if (backPressedTime + 2000 > System.currentTimeMillis()) {
super.onBackPressed();
return;
} else {
Toast.makeText(getBaseContext(), "Press back again to exit", Toast.LENGTH_SHORT).show();
}
backPressedTime = System.currentTimeMillis();
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
webview = (WebView) findViewById(R.id.webView);
webview.setWebViewClient(new WebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setDomStorageEnabled(true);
webview.setOverScrollMode(WebView.OVER_SCROLL_NEVER);
webview.loadUrl("https://www.myurl.com");
}
}
Any help would be greatly appreciated. Thank you

You can override URL loading with following code. If you want to handle URL loading yourself return true. If the URL should be opend in the WebView, return false.
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Insert logic here
}
}
If you just want to open external links you can use following code. In case the opened URL starts with your domain's base URL, false is returned and the URL is opened in the WebView. Otherwise the ACTION_VIEW intent is used to open the URL in the browser and true is returned.
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// Abort if no URL
if (url == null || !(url.startsWith("http://") ||
url.startsWith("https://"))) {
return false;
}
// Abort if internal URL
if (url.startsWith("http://www.myurl.com") ||
url.startsWith("https://www.myurl.com")) {
return false;
}
// Open external URL in browser
startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
}
});
Notice: You have to handle "http://..." and "https://...". Because the method might get called for both.

Related

open all website URL within App and external URLs using external browser in WebView?

I have this code, but not because it works, it keeps opening in webview and what I want is that the links do not belong to my website open in your default browser. Any idea? thanks
here is my MainActivity.java
package club.moviestreet.www.webviewapp;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MainActivity extends AppCompatActivity {
private WebView mywebView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mywebView = (WebView) findViewById(R.id.webview);
WebSettings webSettings= mywebView.getSettings();
webSettings.setJavaScriptEnabled(true);
mywebView.loadUrl("http://moviestreet.club/");
// Line of Code for opening links in app
mywebView.setWebViewClient(new WebViewClient());
}
//Code For Back Button
#Override
public void onBackPressed() {
if(mywebView.canGoBack())
{
mywebView.goBack();
}
else
{
super.onBackPressed();
}
}
}
What you need is shouldOverrideUrlLoading of WebViewClient
Give the host application a chance to take over the control when a new url is about to be loaded in the current WebView. If WebViewClient is not provided, by default WebView will ask Activity Manager to choose the proper handler for the url. If WebViewClient is provided, return true means the host application handles the url, while return false means the current WebView handles the url.
Replace
mywebView.setWebViewClient(new WebViewClient());
With this:
mywebView.setWebViewClient(new WebViewClient() {
#SuppressWarnings("deprecation")
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (!url.startsWith("http://moviestreet.club/")) {
Intent i = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(i);
return true;
}
return false;
}
});

Get URL From WebView

I was wondering if there exits another effective way to get the URL that will load up on the WebView. My current code gives the current Url and not the one that will be loaded.
For example if my WebView load this: http://stackoverflow.com
After loading If I click on Questions, I would not get this url http://stackoverflow.com/questions, for some reason I would get http://stackoverflow.com
So my question is how would you get the url that will be loading on a WebView?
This is my code, please help!
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class MainActivity extends Activity {
// Declaring
WebView browser;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Initializing
browser = (WebView) findViewById(R.id.webView1);
browser.getSettings().setJavaScriptEnabled(true);
browser.getSettings().setLoadWithOverviewMode(true);
browser.getSettings().setUseWideViewPort(true);
browser.getSettings().setBuiltInZoomControls(true);
// Loading
browser.loadUrl("http://stackoverflow.com");
browser.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
return true;
}
public void onLoadResource(WebView view, String url) {
//here I get the Url, but its not accurate. Sometimes it works, sometiems it doesn't
Toast.makeText(getApplicationContext(), browser.getUrl(),
Toast.LENGTH_SHORT).show();
}
});
}
}
Try to get url from this function :
EDIT:
browser.loadUrl("http://stackoverflow.com");
browser.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
Toast.makeText(getApplicationContext(), url, Toast.LENGTH_SHORT).show();
Log.v("TEST", url);
if(url.equals("http://stackoverflow.com/questions")){
Toast.makeText(getApplicationContext(), "SKIP", Toast.LENGTH_SHORT).show();
}
else{
view.loadUrl(url);
}
return true;
}
});
Reference :
shouldOverrideUrlLoading
I know its very late but,for other users if it helps it would be my pleasure.
In ur WebViewClient u can use :
private class MyWebViewClient extends WebViewClient {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
String webUrl=view.getUrl();
return true;
}
}

What's the place of this code about urls in webview?

I want to add this code to my java file:
webView.setWebViewClient(new WebViewClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null && url.startsWith("http://")) {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
} else {
return false;
}
}
}
But I don't know where. This is my java file:
package sherdle.donald.duck.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebPageLoader extends Activity
{
WebView webview;
final Activity activity = this;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webview.getSettings().setSupportMultipleWindows(true);
webview.getSettings().setPluginsEnabled(true);
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle("Loading...");
activity.setProgress(progress * 100);
if(progress == 100)
activity.setTitle(R.string.app_name);
}
});
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webview.loadUrl("http://www.sherdle.com/apphosting/dd");
}
#Override
public void onBackPressed (){
if(webview.canGoBack()) webview.goBack();
else super.onBackPressed();
}
}
I'm new to android and I need much help for everything I do. Thanks for your help.
I've got already this now:
package sherdle.donald.duck.app;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class WebPageLoader extends Activity
{
WebView webview;
final Activity activity = this;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webview.getSettings().setSupportMultipleWindows(true);
webview.getSettings().setPluginsEnabled(true);
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle("Loading...");
activity.setProgress(progress * 100);
if(progress == 100)
activity.setTitle(R.string.app_name);
}
});
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webview.setWebChromeClient(new WebChromeClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null && url.startsWith("http://")) {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
} else {
return false;
}
}
webview.loadUrl("http://www.sherdle.com/apphosting/dd");
}
#Override
public void onBackPressed (){
if(webview.canGoBack()) webview.goBack();
else super.onBackPressed();
}
}
But I get this error on my LoadUrl line:
Multiple markers at this line
- Syntax error, insert "AssignmentOperator Expression" to complete
Expression
- Syntax error, insert ";" to complete FieldDeclaration
- Syntax error, insert ")" to complete MethodInvocation
- Syntax error, insert "}" to complete ClassBody
- Syntax error, insert ";" to complete Statement
- Syntax error on token(s), misplaced construct(s)
use in this way
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.getSettings().setJavaScriptEnabled(true);
webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
webview.getSettings().setSupportMultipleWindows(true);
webview.getSettings().setPluginsEnabled(true);
webview.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle("Loading...");
activity.setProgress(progress * 100);
if(progress == 100)
activity.setTitle(R.string.app_name);
}
});
webview.setWebViewClient(new WebViewClient() {
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webview.setWebChromeClient(new WebChromeClient(){
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url != null && url.startsWith("http://")) {
view.getContext().startActivity(
new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
return true;
} else {
return false;
}
}
});
webview.loadUrl("http://www.sherdle.com/apphosting/dd");
}
#Override
public void onBackPressed (){
if(webview.canGoBack()) webview.goBack();
else super.onBackPressed();
}
First make sure you have webview in your layout. Also make sure you have the following line in your manifest.
<uses-permission android:name="android.permission.INTERNET" />
Then you add that in your onCreate. It may not be the best, but it'll suffice.
Sorry, but how can you not understand where to insert that piece of code if you have exactly that same method already overridden? Look where it says:
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
If you want to change the behaviour above, simply replace these two lines specified by that in the first code snippet.
I've got a feeling you don't really understand anonynous inner classes, as you also try to set a WebChromeClient twice - that doesn't really make sense. I suggest you do some reading on the matter.
Also, the shouldOverrideUrlLoading(...) method is defined by a WebViewClient, not a WebChromeClient. That's a case of simply consulting the documentation.

How to add back button to Android Web App

I'm trying to sort out a web app but cannot find a possible way to include the use of a back button via the phone's soft keys. How can I go about doing this?
i.e I want to use the back button on my phone to return to the previous viewed web page.
Thank you
Jordan
package com.wear2gym;
import android.app.Activity;
import android.os.Bundle;
import android.view.Window;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.Toast;
public class Wear2gym extends Activity
{
final Activity activity = this;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
this.getWindow().requestFeature(Window.FEATURE_PROGRESS);
setContentView(R.layout.main);
WebView webView = (WebView) findViewById(R.id.WebView);
webView.getSettings().setJavaScriptEnabled(true);
webView.setWebChromeClient(new WebChromeClient() {
public void onProgressChanged(WebView view, int progress)
{
activity.setTitle("Pumping some iron...");
activity.setProgress(progress * 100);
if(progress == 100)
activity.setTitle(R.string.app_name);
}
});
webView.setWebViewClient(new WebViewClient() {
#Override
public void onReceivedError(WebView view, int errorCode, String description, String failingUrl)
{
Toast.makeText(activity, "Sorry but there is no internet connection! " , Toast.LENGTH_LONG).show();
view.loadUrl("file:///android_asset/nointernet.html");
// Handle the error
}
#Override
public boolean shouldOverrideUrlLoading(WebView view, String url)
{
view.loadUrl(url);
return true;
}
});
webView.loadUrl("http://wear2gym.co.uk");
webView.canGoBack();
}
}
I wouldn't recommand onBackPressed() as thatÅ› only available since API level 5
You will find great info here: http://developer.android.com/guide/webapps/webview.html
#Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
// Check if the key event was the Back button and if there's history
if ((keyCode == KeyEvent.KEYCODE_BACK) && myWebView.canGoBack() {
myWebView.goBack();
return true;
}
// If it wasn't the Back key or there's no web page history, bubble up to the default
// system behavior (probably exit the activity)
return super.onKeyDown(keyCode, event);
}
override the onBackPressed() method:
#Override
public void onBackPressed() {
if(mWebView.canGoBack()) {
mWebView.goBack();
}
else {
super.onBackPressed();
}
}
This will go back on the WebView until it can't go back, in which case it will exit the Activity

Opening tel: & mailto: links in Android WebViewClient

I have been looking for an answer to this question that I can understand for the last couple of days. After trying all of the code snippets online that I have seen I am still having difficulties. I am very new to the android sdk and java, actually this is my first shot at writting an Android app. So my question is this, how come I keep getting the ever so famous error "Page cant be displayed" when clicking on a mailto or tel link ?
Here is my code:
package com.mine.mobile;
import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.webkit.WebView;
import android.webkit.WebViewClient;
public class MineActivity extends Activity {
/** Called when the activity is first created. */
/**#Override */
WebView webview;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
webview = (WebView) findViewById(R.id.webview);
webview.setWebViewClient(new WebViewClient());
webview.getSettings().setJavaScriptEnabled(true);
webview.loadUrl("http://my.mobilesite.com");
}
public boolean shouldOverrideUrlLoading(WebView view, String url) {
if (url.startsWith("tel:")) {
startActivity(new Intent(Intent.ACTION_DIAL, Uri.parse(url)));
return true;
} else if (url.startsWith("mailto:")) {
url = url.replaceFirst("mailto:", "");
url = url.trim();
Intent i = new Intent(Intent.ACTION_SEND);
i.setType("plain/text").putExtra(Intent.EXTRA_EMAIL, new String[]{url});
startActivity(i);
return true;
} else if (url.startsWith("geo:")) {
Intent searchAddress = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
startActivity(searchAddress);
}
else {
view.loadUrl(url);
return true;
}
return true;
}
}
You put the method in your Activity. It needs to override the method in WebView. For example:
webview.setWebViewClient(new WebViewClient() {
public boolean shouldOverrideUrlLoading(WebView view, String url) {
...
}
}

Categories

Resources