Android WebView err_unknown_url_scheme

后端 未结 5 703
花落未央
花落未央 2020-11-27 05:11

With the simple below code I can get my url loaded correctly, but, I get \"ERR_UNKNOWN_URL_SCHEME\" when trying to tap on html links that starts with mailto: wh

5条回答
  •  无人及你
    2020-11-27 06:10

    You need override the method shouldOverrideUrlLoading of WebViewClient in which you can control link transfer by yourself.

    Because html links that starts with mailto: whatsapp: and tg: (Telegram). is not common url start with "http://" or "https://", so WebView cannot parse it to right place, we should use intent to redirect the url.

    For example:

            @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;
                }
            }
    

    then setWebViewClient to your WebView, like this:

    public class MainActivity extends Activity {
    
    private WebView mWebView;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
    
        mWebView = (WebView) findViewById(R.id.activity_main_webview);
    
        // Force links and redirects to open in the WebView instead of in a browser
        mWebView.setWebViewClient(new WebViewClient() {
    
        @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;
            }
        }
        });
    
        // Enable Javascript
        WebSettings webSettings = mWebView.getSettings();
        webSettings.setJavaScriptEnabled(true);
    
        // Use remote resource
        mWebView.loadUrl("http://myexample.com");
    }}
    

提交回复
热议问题