handling links in a webview

后端 未结 3 2116
滥情空心
滥情空心 2020-11-30 00:31

I have my WebView loading all links inside the webview - but when I select an email link it tries to load it in the webview instead of launching an email app on

3条回答
  •  慢半拍i
    慢半拍i (楼主)
    2020-11-30 01:20

    Going off of the answer provided by @schwiz, here is a cleaner example. Assuming the WebView is named webView:

    webView.setWebViewClient(new WebViewClient() {
        // shouldOverrideUrlLoading makes this `WebView` the default handler for URLs inside the app, so that links are not kicked out to other apps.
        @Override
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            // Use an external email program if the link begins with "mailto:".
            if (url.startsWith("mailto:")) {
                // We use `ACTION_SENDTO` instead of `ACTION_SEND` so that only email programs are launched.
                Intent emailIntent = new Intent(Intent.ACTION_SENDTO);
    
                 // Parse the url and set it as the data for the `Intent`.
                emailIntent.setData(Uri.parse(url));
    
                // `FLAG_ACTIVITY_NEW_TASK` opens the email program in a new task instead as part of this application.
                emailIntent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
    
                // Make it so.
                startActivity(emailIntent);
                return true;
            } else {  
                // Returning false causes WebView to load the URL while preventing it from adding URL redirects to the WebView history.
                return false;
            }
        }
    });
    

    I have tested this with all the mailto: options: multiple email addresses, CC, BCC, subject, and body.

提交回复
热议问题