LoginSignup
12
12

More than 5 years have passed since last update.

AndroidでWebViewを使用する際の注意点

Last updated at Posted at 2012-04-20

Androidのアプリ内でWebViewを使用する際に、サイトページ内に、window.open(url)やwindow.location.href=urlを使用したが画面遷移があると、うまく画面遷移ができない。

解決策は、shouldOverrideUrlLoadingをオーバーライドして、各種サービスの起動を明記する。

下記例では、urlが、「mailto:」で始まった時はメールアプリを起動する暗黙的インテントを発行し、TwitterやFacebookのシェアボタンをタップした時には、画面遷移先を読み込むようにしている。

CustomWebView.java
        wb = (WebView) findViewById(R.id.event_wb);
        wb.setWebChromeClient(new WebChromeClient());
        wb.setWebViewClient(new WebViewClient() {
            @Override
            public boolean shouldOverrideUrlLoading(WebView webView, String url) {
                Intent intent = null;
                if(url.substring(0, 7).equals("mailto:"))
                    intent = new Intent(Intent.ACTION_SENDTO, Uri.parse(url));
                else if(url.contains("twitter") || url.contains("facebook"))
                    intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                if(intent != null) {
                    startActivity(intent);
                    webView.reload();   
                }
                return true;
            }
        });
        WebSettings settings = wb.getSettings();
        settings.setJavaScriptEnabled(true);
12
12
1

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
12
12