10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

WebViewから文字列を抽出する方法

Last updated at Posted at 2014-06-25

WebViewから文字列を抽出する方法

ある文字列しか返さないHTMLを取得してその後の処理を分けるという要件があったのでメモ。

htmlの中身はこんだけ↓
特にタグとかは無し。

index.html
test・・・・・

取得方法↓

        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                Bundle savedInstanceState) {
            View rootView = inflater.inflate(R.layout.fragment_my, container, false);
            final WebView webView = (WebView) rootView.findViewById(R.id.webview);
            webView.getSettings().setJavaScriptEnabled(true);
            webView.addJavascriptInterface(new JavaScriptInterface(), "showHtml");

            webView.setWebViewClient(new WebViewClient() {
                @Override
                public void onPageFinished(WebView view, String url) {
                    webView.loadUrl("javascript:window.showHtml.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
            }
            });

            webView.loadUrl("http://xxxx.xxx/test.html");

            return rootView;
        }
    }
    class JavaScriptInterface {
        @SuppressWarnings("unused")
        public void showHTML(String html) {
            Log.d("html", html);
            Spanned spanned = Html.fromHtml(html);

            // これでHTMLの中身が文字列で取得可能
            String target = spanned.toString();
            if (TextUtils.equals(target, "xxxxxx")) {
                // TODO ここで処理を分ける
            } else {
            
            }
            
        }
    }

要はJavascriptを強制的に埋め込んで、JSでJavaのメソッドにHTMLの中身つけて呼んであげるという強引な方法です。

引用

http://lexandera.com/2009/01/extracting-html-from-a-webview/

10
10
0

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
10
10

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?