Webview loadurl error

I want to load the URL in WebView I have used the following Code: webView = (WebView) findViewById(R.id.webview1); webView.setWebViewClient(new HostsWebClient()); webView.getSettings().setPluginS...

First, check if you have internet permission in Manifest file.

<uses-permission android:name="android.permission.INTERNET" />

You can then add following code in onCreate() or initialize() method-

final WebView webview = (WebView) rootView.findViewById(R.id.webview);
        webview.setWebViewClient(new MyWebViewClient());
        webview.getSettings().setBuiltInZoomControls(false);
        webview.getSettings().setSupportZoom(false);
        webview.getSettings().setJavaScriptCanOpenWindowsAutomatically(true);
        webview.getSettings().setAllowFileAccess(true);
        webview.getSettings().setDomStorageEnabled(true);
        webview.loadUrl(URL);

And write a class to handle callbacks of webview —

public class MyWebViewClient extends WebViewClient {
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
                           //your handling...
                return super.shouldOverrideUrlLoading(view, url);
        }
    }

in same class, you can also use other important callbacks such as —

- onPageStarted()
- onPageFinished()
- onReceivedSslError()

Also, you can add «SwipeRefreshLayout» to enable swipe refresh and refresh the webview.

<android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/swipeRefreshLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent">
        <WebView
            android:id="@+id/webview"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />
    </android.support.v4.widget.SwipeRefreshLayout>

And refresh the webview when user swipes screen:

SwipeRefreshLayout mSwipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipeRefreshLayout);
            mSwipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
                @Override
                public void onRefresh() {
                    new Handler().postDelayed(new Runnable() {
                        @Override
                        public void run() {
                            mSwipeRefreshLayout.setRefreshing(false);
                            webview.reload();
                        }
                    }, 3000);
                }
            });

The err_unknown_url_scheme error usually comes up during Android WebView app development when a developer has chosen links to have mailto://, whatsapp://, or any other intent that’s not the basic http:// or https://. Specific URL coding needs to be added to handle these difference URL schemes to prevent this error.

err_unknown_url_scheme error message

The discussion and solutions for this article are directed towards Android developers. If you are a user and run into this error, there’s nothing you can do to immediately solve the problem. Your best course of action would be to contact the app  developer to make sure they are aware of this bug.

Android Dominance

Android is the dominant operating system (OS) for mobile devices. Android boasts a 71% market share, followed by Apple’s iOS with 27% market share. Google bought Android Inc. in 2005 in order to have control over Android’s future development and to load Android OS on all of its mobile devices. All other major mobile device manufacturers, besides Apple, use Android. Samsung, OnePlus, Huawei, Motorola, Nokia, LG, and Sony devices all come preloaded with the Android OS. It’s also significantly easier to develop and host an app on Google’s Play Store than on Apple’s App Store.

These factors have contributed to a robust Android developer community. Android developers use meetups and conferences, slack and Reddit, blogs and forums, and Stack Overflow to communicate and learn from each other. Many developers are self-taught and rely on the insights of the Android community to overcome persistent programming errors and bugs.

Android Studio is the only official development environment for Android. Android Studio was built using JetBrains’ software, the same company responsible for a variety of other popular IDEs (integrated development environments) for languages like Python (Pycharm), PHP (PhpStorm), and Java (IntelliJ IDEA).

Android Studio dashboard

Native apps live in the Google Play Store or App Store. They are fully developed applications that are installed directly onto the mobile device. Native apps will maintain most of their functionality even when not connected to the internet or mobile networks. These differ from web apps, which are simply websites. Web applications are easier to develop but don’t have access to any system features like GPS.

As a developer you may want to build a native app but still provide access to web content. This is done using WebView. WebView is a special class that allows web content to be displayed within your native app. For example, if you have the native Facebook app on your phone and click an external link, the webpage will load within the app. You can navigate around on the loaded webpage, access other parts of the webpage, shop, and interact. The embedded browser will not have an address bar for your user to search with. This provides the developer a way to have both the benefits of a web app and a native app.

WebView is set to handle certain URL schemes. If you try to use a special URL scheme outside the standard https:// and http://, WebView can throw the err_unknown_url_scheme error. A few of the non-standard URL schemes that WebView isn’t set to recognize are:

  • mailto://
  • whatsup://
  • file://
  • telnet://
  • intent://
  • market://
  • app://
WebView app development in Android Studio

3 ways to fix the err_unknown_url_scheme error

To solve this error, you can go one of two routes: either disable those schemes and only develop your app using http:// and https:// schemes, or you can edit your code to be able to handle these specific URL schemes. The first option is not an absolute solution but can fix the problem in some use cases. The second solution shows examples of how to add new intents for URL schemes, and the third solution involves disabling any non-standard URL schemes.

1. Open In New Window

A quick and easy stopgap solution is editing your URL href code. By adding target=”_blank” you are able to solve the problem in a roundabout way. Now adding this snippet of code can have an undesirable development effect because this link will now open in a new window.

Development best practice is to avoid opening extra browser windows. This is because a new browser can bother or confuse your user. By removing the ‘back’ button, users find it more difficult to navigate and get back to their previous page in your app. The standard is target=”_self”, which opens the link in the same browser page.

Below is an example of URL href code with target=”_blank” added in:

<a href= “tel:555-111-5555” target=”_blank”> Contact Me </a>

Or:

<a href=”mailto:myname@gmail.com” target=”_blank”> Email Me </a>

2. Add New Intent to Load in External App

In Android development, intents are used to tell Android what you want the app to do, essentially allowing you to call a specific action or component. Some scheme errors can be fixed by adding an intent to load in an external app. For example, loading mailto:// in an external app should cause the email link to open in your default email application. Another example is maps:// which should open in your default maps application.

In the code snippet below, you will be using an IF statement to handle this. Any URL that starts with http:// or https:// is ignored and opened as usual. Otherwise, if the URL involves a special scheme such as:

  • tel://
  • sms://
  • mailto://
  • geo://
  • maps://

then a new intent is added to load the action in an external app. If the activity cannot be successfully started because no associated external app exists on that system, an error will appear to the user.

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
    if (url == null || url.startsWith("http://") || url.startsWith("https://")) {
        return false;
    } 

    try {
        Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
        view.getContext().startActivity(intent);
        return true;
    } catch (Exception e) {
        Log.i(TAG, "shouldOverrideUrlLoading Exception:" + e);
        return true;
    }
}

Another code snippet is included below to show that you can tackle this problem in a variety of ways. This method overrides URL loading like seen above and should open a related app to carry out the protocol. If the associated application, in this case Whatsapp is not installed, a message is displayed for your user. This message is called a toast message and gives the user an idea on what went wrong and how to fix it. The toast message for this scheme was ‘Whatsapp has not been installed’.

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);

    if (url.startsWith("whatsapp://")) {
        webview.stopLoading();
        try {
            Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
            whatsappIntent.setType("text/plain");
            whatsappIntent.setPackage("com.whatsapp");

            whatsappIntent.putExtra(Intent.EXTRA_TEXT, webview.getUrl() + "  - Shared from webview ");

            startActivity(whatsappIntent);
        } catch (android.content.ActivityNotFoundException ex) {

            String MakeShortText = "Whatsapp has not been installed";

            Toast.makeText(WebactivityTab1.this, MakeShortText, Toast.LENGTH_SHORT).show();
        }
    };
};

3. Disable any non-standard URL schemes

By disabling URL schemes other than the standard https:// and http:// you are bypassing this problem completely. You won’t be able to use any custom schemes like the ones listed earlier in the article.

If your app has one of these schemes or a user somehow navigates to a link using these schemes, a toast message will appear. The message “Error: Unknown link type” will tell the user they can’t proceed. Below is an example of this method:

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);
if (url.startsWith("http") || url.startsWith("https")) {
    return true;
}else {
    webview.stopLoading();
    webview.goBack();
    Toast.makeText(MainActivity.this, "Error: Unknown link type", Toast.LENGTH_SHORT).show();
}
return false;
}

WebView Has Great Benefits, But Some Creative Coding Is Needed

Android WebView really provides the best of both worlds for Android developers, but creative workarounds are needed for some situations. By using WebView to display an embedded browser within your native app, you gain all the benefits of both the native app and a web app. You will be able to use the native system APIs in your web code which is usually constrained.

If you are developing an app and want to include special URLs, outside of http:// and https:// you will need to add some intents or fall back URLs, otherwise your our users will experience the error “err_unknown_url_scheme”. When a URL like mailto:// or maps:// is called, your code needs to open an associated external app that can complete that action. Otherwise you can disable these other URLs and set a specific error message to any users that stumbles upon a link with one of these URL schemes.

Issue

Using webView.loadUrl is working for https site , but not with my local page which is located in /Applications/MAMP/htdocs/test.html

webView.loadUrl("/Applications/MAMP/htdocs/test.html") is not working
webView.loadUrl("http://localhost:8080/test.html"); is not working

Below is the test.html file

<!DOCTYPE html>
<html>
<head>
<title>Sample Page</title>
</head>
<body>

<h2>JS alert Example</h2>

<button onclick="myFunction()" >Try it</button>

<script>
function myFunction (){
    Android.showToast("Sample Android toast message");
}
</script>

</body>
</html>

Now I want to load this page using webView .

Below is the mainactivity.java code

    public class MainActivity extends AppCompatActivity {
    private WebView webView;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        getSupportActionBar().hide();
        webView = (WebView) findViewById(R.id.webview);
        webView.loadUrl("http://127.0.0.1:8080/test.html");

        WebSettings webSettings = webView.getSettings();
        webSettings.setJavaScriptEnabled(true);
        webView.setWebViewClient(new WebViewClient());
        webView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);
        webView.addJavascriptInterface(new WebAppInterface (this), "Android");



    }
}

Below is my WebInterface java class :

public class WebAppInterface {

    private Context context;

    public WebAppInterface (Context context){
        this.context = context;
    }

    @JavascriptInterface
    public void showToast (String message){
        Toast.makeText(context,message,Toast.LENGTH_LONG).show();
    }
}

Now ,I cant understand why it is not loading the web page mentioned in webView.loadUrl . Note: I having given internet permissions in manifest file.

Solution

So if the file is local in the device (android phone), you need to have the path of the file. If the file is bundled in the assets, you can open the file like:

webView.loadUrl("file:///android_asset/filename.html");

Or if you can’t find it, you can put the file in the raw resources and read the file into a string and then use:

webView.loadData(htmlString, "text/html", "utf-8");

In any case, most probably the problem you have is you can’t find the file. So make sure you are placing the file in the proper place in the assets, or resources. And you are accessing the file correctly.

Here is the documentation on how to access the resources:
https://developer.android.com/guide/topics/resources/providing-resources

If what you mean by local is on your computer, and you are hosting the file (which I assume would be just for testing), then you need to connect the android device / emulator to the same local network as your computer and then access via the local ip of your computer.

And here is another question similar to this that has already been answered:
Load HTML file into WebView

Answered By — juancamilo87

  • Remove From My Forums
  • Question

  • User148620 posted

    Dear members,

    I’m trying to execute a JS code in my new hybrid-app, I’m new with Xamarin and I’m not able to execute it, I’m just able to run the html. This is my current code:
    C#
    WebView webView;
    webView = FindViewById(Resource.Id.webView);

                    webView.LoadUrl("file:///android_asset/index.html");
    
                    webView.Settings.JavaScriptEnabled = true;
    
                    string script = string.Format("javascript:UpdateData('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}');", allDishes[0].name, allDishes[0].ingredients, allDishes[0].portions, allDishes[0].time1, allDishes[0].time2, allDishes[0].recipe, allDishes[0].copyright, allDishes[0].video, "file:///android_asset/" + allDishes[0].image);
    
                    if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
                    {
                        webView.EvaluateJavascript(script, null);
                    }
                    else
                    {
                        webView.LoadUrl(script);
                    }
    

    JS:

            function UpdateData(arg1, arg2, arg3, arg4, arg5, arg6, arg7, arg8, arg9) {
                alert("Hi");
        }
    

    Do anyone know what should I change? It’s not executing at all the JS. Thanks for your help.

Answers

  • User148620 posted

    If anyone has a similar problem Martin Zikmund provided me a solution in StackOverflow:

    First we need to create a class like this one:

    public class JavaScriptWebViewClient : WebViewClient
    {
        public override void OnPageFinished(WebView view, string url)
        {
            base.OnPageFinished(view, url);
    
            string script = string.Format("javascript:UpdateData('{0}','{1}','{2}','{3}','{4}','{5}','{6}','{7}','{8}');", "1", "2", "3", "4", "5", "6", "7", "8", "9");
    
            if (Build.VERSION.SdkInt >= BuildVersionCodes.Kitkat)
            {
                view.EvaluateJavascript(script, null);
            }
            else
            {
                view.LoadUrl(script);
            }
        }
    }
    

    Later apply it to the WebView:

    var webView = FindViewById<WebView>(Resource.Id.webView);
    webView.SetWebChromeClient(new WebChromeClient());
    webView.Settings.JavaScriptCanOpenWindowsAutomatically = true;
    webView.Settings.JavaScriptEnabled = true;
    
    //set the custom web client
    webView.SetWebViewClient(new JavaScriptWebViewClient());
    
    webView.LoadUrl("file:///android_asset/index.html");
    

    And it works like magic!

    Some additional information:
    https://stackoverflow.com/a/40759071/2889347

    • Marked as answer by

      Thursday, June 3, 2021 12:00 AM

The unknown url error screen

Fix err_unknown_url_scheme intent://,whatsapp:// etc in Android WebView

Updated on March 4, 2022

This error is appeared in your android webview app because the WebView can’t recognize the special URL Schemes

For example, the WebView will usually recognize http and https, anything other than these, for example – intent://, market://, tel://, mailto:// , whatsapp:// etc will not be recognized by WebView unless we add a handler code to handle these url schemes, or by disabling these schemes and only load http and https schemes.

What are URL schemes in android?

The url schemes like intent://, market://, app://, mailto:// etc are special URL schemes in the webview that can be used to open apps from webview, invoke an android activity or do an action etc. For example, the mailto:// url scheme can be used to send email action directly from the webview.

You can even make your own url scheme and make the webview recognize it so the webview can do your own action that you define

Another example is market://, this can be used to open google playstore action from the webview, another example is whatsapp://, this can be used to directly share a text or link from webview to whatsapp messenger.

If we do not set actions whenever the special url schemes are invoked, it will show the unknown url scheme error. It is possible to stop showing the error screen with a few lines of code, but it is better to fix this error by adding additional code to handle the the url schemes. The additional code can be complex but we can help you.

We have built a webview app template after months of research, the app template now supports most url schemes, i suggest you try the template and you will not need look back and stress to fix the url schemes error, the template is easy to use

Save your time and stress, use our Advanced Webview Template

You can use our Advanced Webview Easy App Template that supports most url schemes and intents to open external apps such as Whatsapp, google playstore, email, tel etc. This template can be imported to android studio and you can change a few things to create a functional webview app and create apks, no more coding because most functions are built in already!

This template also supports the following things:

  • File upload
  • File download
  • Onesignal notifications
  • Drawer menu, bottom navigation bar, option menu
  • GPS access, dark theme and many other features.

This template will save your stress and time. Your full functional webview app for your website now can be easily built and ready in less than an hour using this app template.

All you need is set an app icon, set your website link, change some colors, change app and package name to turn the template to your desired android webview app that supports almost all webview functions. You can download the demo APK to test the uri functions

If you want it, head to this page Download Android Webview Source Code Template.

How to Disable the Url Scheme Error Screen in Android

We can totally disable the error by writing a few lines of code in the onPageFinished and ShouldOverrideUrlLoading

but the problem here is that webview will not handle the schemes, so if you need open the mail app, the mail:// will not work, only https and http links will be handled by webview

Here is how to disable other url schemes and allow only http and https

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 {

    String url = "http://www.google.com";
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.webactivity);


        final WebView webview = (WebView) findViewById(R.id.web1);
        webview.loadUrl(url);

        webview.setWebViewClient(new WebViewClient(){

        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);

            if (url.startsWith("http") || url.startsWith("https")) {
                return true;
            }else {
                webview.stopLoading();
                webview.goBack();
                Toast.makeText(MainActivity.this, "Unknown Link, unable to handle", Toast.LENGTH_SHORT).show();
            }
            return false;



}});}}

How to set actions for these special url schemes

You can set actions to any of the url schemes with the onPageFinished  method in the webview

Here is an example

The code here is executed if the clicked url in the webview starts with whatsapp://,  if whatsapp is already installed, then the webview will attempt to share the current page link to whatsapp, if whatsapp is not installed, it will show a toast message

@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
view.loadUrl(url);

                if (url.startsWith("whatsapp://")) {
                    webview.stopLoading();
                    try {
                        Intent whatsappIntent = new Intent(Intent.ACTION_SEND);
                        whatsappIntent.setType("text/plain");
                        whatsappIntent.setPackage("com.whatsapp");

                        whatsappIntent.putExtra(Intent.EXTRA_TEXT, webview.getUrl() + "  - Shared from webview ");

                        startActivity(whatsappIntent);
                    } catch (android.content.ActivityNotFoundException ex) {

                        String MakeShortText = "Whatsapp have not been installed";

                        Toast.makeText(WebactivityTab1.this, MakeShortText, Toast.LENGTH_SHORT).show();
                    }


                }
                ;

            }});

Another examples

Here is an example to fix the common intent url scheme , we will learn how to handle the intent:// here , i noticed this error when i built an app that loads facebook messages, the error appeared whenever i tap on the message icon of facebook. i suppose this is because the facebook is sending you to app store to download the messenger app when you tap on the message icon. In the below code, we will fix it.

The Code to Fix err_unknown_url_scheme intent://

webview.setWebViewClient(new WebViewClient() {
           String currentUrl;

           @Override
           public boolean shouldOverrideUrlLoading(WebView view, String url) {
               currentUrl = url;

               if (url.startsWith("http") || url.startsWith("https")) {
                   return false;
               }
               if (url.startsWith("intent")) {




                 try {
                     Intent intent = Intent.parseUri(url, Intent.URI_INTENT_SCHEME);

                     String fallbackUrl = intent.getStringExtra("browser_fallback_url");
                   if (fallbackUrl != null) {
                       webview.loadUrl(fallbackUrl);
                       return true;
                   }}

               catch (URISyntaxException e) {
                   //not an intent uri
               }
       return true;//do nothing in other cases

What we did in this code is whenever the url we clicked contain intent:// scheme, we try to override it and get the fallbackUrl to the string, then we try to load the url. this should fix the intent error

You can set your own scheme handler for your apps from these examples


Update: If you are new to android development, or just want fix this url scheme error code, i can fix it for you for a small fee of US $5. Just send me your project  (export to zip) or that java or kotlin file (The MainActivity or the Activity where you wish to fix url scheme) through email or google drive, i will fix your project or file and send it back to you. I can also do it through TeamViewer or AnyDesk

You can pay through Paypal , GooglePay, PayTM, PhonePe or any payment method your country supports. For more details, contact me through:

  • WhatsApp: Send WhatsApp Message (+91 963303 9471)
  • Call: Click to call
  • Telegram: Telegram Message
  • Email: [email protected]

If you want convert your website to android app in just 2 hours, we can do it, see this page Online Android App Builder
If you want a very advanced webview source code see this page Download Android Webview App Source Code Template

{SOLVED} Error Unknown Url Scheme in Android Webview

Today in this post, we will solve an error when we try to open a url in webview which wants to open a specific app. For Eg. when we open instagram.com in our android webview, there’s a button of open in app, when we click on that button it will show us an error of unknown url scheme. we will solve this error in this post.

To create a full WebView click here 

  • There are two methods of shouldoverrideurlloading in android webview webclient.
  • We will use the method which has webresourcerequest and Webview arguments.
  • shouldoverriddeurlloading method is called when we click on a button or Url in android webview
  • We will start activity intent on a button click
  • When url starts with intent:// , whatsapp:// etc. we should have handle clicking that url
  • We can put conditions of checking url with these keywords or start url without conditions.

Java code with full webclient, see that method carefully

 mywebview.setWebViewClient(new WebViewClient() {  
       @Override  
       public void onPageStarted(WebView view, String url, Bitmap favicon) {  
         progressbar.setVisibility(View.VISIBLE);  
         tooltext.setText(mywebview.getUrl());  
         invalidateOptionsMenu();  
         final String Urls = url;  
   
         if (Urls.contains("mailto:") || Urls.contains("sms:") || Urls.contains("tel:")) {  
           mywebview.stopLoading();  
           Intent i = new Intent();  
           i.setAction(Intent.ACTION_VIEW);  
           i.setData(Uri.parse(Urls));  
           startActivity(i);  
         }  
   
         super.onPageStarted(view, url, favicon);  
       }  
   
       @Override  
       public void onPageFinished(WebView view, String url) {  
         progressbar.setVisibility(View.GONE);  
         invalidateOptionsMenu();  
   
         addhistory();  
   
         tooltext.setText(mywebview.getUrl());  
         super.onPageFinished(view, url);  
       }  

//This code is used to handle url scheme. See the method carefully

       @RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)  
       @Override  
       public boolean shouldOverrideUrlLoading(WebView view, WebResourceRequest request) {  
   
         mywebview.loadUrl(String.valueOf(request.getUrl()));  
   
         //if you want to open a specific activity from webview  
         if( String.valueOf(request.getUrl()).startsWith("whatsapp://"))  
         {  
           mywebview.stopLoading();  
   
           try {  
             Intent intent = new Intent(Intent.ACTION_SEND);  
             intent.setType("text/plain");  
             intent.setPackage("com.whatsapp");  
   
             intent.putExtra(Intent.EXTRA_TEXT,mywebview.getUrl());  
             startActivity(intent);  
           }  
           catch(Exception e){  
   
         }  
         }  
   
         //if you want to open an activity chooser  
         // our url scheme starts with intent, if app found then it opens that, otherwise it catch exception only  
         try {  
           Intent intent = Intent.parseUri(String.valueOf(request.getUrl()),Intent.URI_INTENT_SCHEME);  
           startActivity(intent);  
           //This works when you open any app, but if you open specific app then  
         }  
         catch(Exception e)  
         {  
   
         }  
   
         return true;  
       }  
   

       @Override  
       public boolean shouldOverrideUrlLoading(WebView view, String url) {  
   
         Log.d("TAG", "shouldOverrideUrlLoading: 3");  
         
           Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));  
           startActivity( intent );  
           
         return true;  
       }  
     });  

Понравилась статья? Поделить с друзьями:
  • Webview android javascript error
  • Websocket protocol error
  • Websocket json error
  • Websocket error undefined
  • Websocket error network error 12030 подключение к серверу было неожиданно прервано