Android Webview获取网页标题和文本内容

通过自定义webview实现类似IOS webview中的stringByEvaluatingJavaScriptFromString方法获取js中的文本简介,代码如下:

public class MyWebView extends WebView {

    public MyWebView(Context context) {
        super(context);
    }

    public MyWebView(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    public MyWebView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
    }

    public String stringByEvaluatingJavaScriptFromString(String script) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            try {
                Field mp = WebView.class.getDeclaredField("mProvider");
                mp.setAccessible(true);
                Object webViewObject = mp.get(this);
                Field wc = webViewObject.getClass().getDeclaredField("mWebViewCore");
                wc.setAccessible(true);
                Object webViewCore = wc.get(webViewObject);
                Field bf = webViewCore.getClass().getDeclaredField("mBrowserFrame");
                bf.setAccessible(true);
                Object browserFrame = bf.get(webViewCore);
                Method stringByEvaluatingJavaScriptFromString = browserFrame.getClass()
                        .getDeclaredMethod("stringByEvaluatingJavaScriptFromString",
                                String.class);
                stringByEvaluatingJavaScriptFromString.setAccessible(true);
                Object obj_value = stringByEvaluatingJavaScriptFromString.invoke(
                        browserFrame, script);
                return String.valueOf(obj_value);
            } catch (Exception e) {
                Log.e("!!!", "stringByEvaluatingJavaScriptFromString", e);
            }
            return null;
        } else {
            try {
                Field[] fields = WebView.class.getDeclaredFields();
                // 由webview取到webviewcore
                Field field_webviewcore = WebView.class.getDeclaredField("mWebViewCore");
                field_webviewcore.setAccessible(true);
                Object obj_webviewcore = field_webviewcore.get(this);
                // 由webviewcore取到BrowserFrame
                Field field_BrowserFrame = obj_webviewcore.getClass().getDeclaredField(
                        "mBrowserFrame");
                field_BrowserFrame.setAccessible(true);
                Object obj_frame = field_BrowserFrame.get(obj_webviewcore);
                // 获取BrowserFrame对象的stringByEvaluatingJavaScriptFromString方法
                Method method_stringByEvaluatingJavaScriptFromString = obj_frame.getClass()
                        .getMethod("stringByEvaluatingJavaScriptFromString", String.class);
                // 执行stringByEvaluatingJavaScriptFromString方法
                Object obj_value = method_stringByEvaluatingJavaScriptFromString.invoke(
                        obj_frame,
                        script);
                // 返回执行结果
                return String.valueOf(obj_value);
            } catch (Exception e) {
                Log.e("!!!", "stringByEvaluatingJavaScriptFromString", e);
            }
            return null;
        }
    }
}

在网页中添加一段js, 包含需要获取文本的字段,如果要兼容微信分享,则定义的变量需和公众号里的是一样的,如下:
这里写图片描述

使用示例:

public class CommonWebActivity extends BaseActivity {

    private MyWebView mWebView;

    private String mTitle = "";
    private String url = "";
    private String msgTitle;//分享标题
    private String msgDesc;//分享描述
    private String msgImgUrl;//分享图片
    private String msgLink;//分享链接
    private boolean canShare = false;//是否支持分享


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_common_webview);
        init();
    }

    private void init() {
        mWebView = (MyWebView) findViewById(R.id.webView);
        WebSettings settings = mWebView.getSettings();
        settings.setJavaScriptEnabled(true);
        settings.setCacheMode(WebSettings.LOAD_NO_CACHE);
        settings.setLoadWithOverviewMode(true);
        settings.setUseWideViewPort(true);
        settings.setJavaScriptCanOpenWindowsAutomatically(true);
        mWebView.setScrollBarStyle(WebView.SCROLLBARS_OUTSIDE_OVERLAY);
        mWebView.setHorizontalScrollBarEnabled(false);
        mWebView.setHorizontalScrollbarOverlay(true);
        mWebView.setWebViewClient(getViewClient());
        mWebView.setWebChromeClient(getChromeClient());

        initIntentData();
        loadData();
    }

    private void initIntentData() {
        Intent intent = getIntent();
        if (null != intent) {
            url = intent.getStringExtra("url");
        }
    }

    private WebViewClient getViewClient() {
        return new WebViewClient(){

            @Override
            public void onPageStarted(WebView view, String url, Bitmap favicon) {
                super.onPageStarted(view, url, favicon);
            }

            @Override
            public void onPageFinished(WebView view, String url) {
                setRightTilteText("分享");
                msgDesc = mWebView.stringByEvaluatingJavaScriptFromString("msg_desc");
                msgTitle = mWebView.stringByEvaluatingJavaScriptFromString("msg_title");
                msgLink = mWebView.stringByEvaluatingJavaScriptFromString("msg_link");
                Log.d(TAG, msgTitle + "/" + msgDesc + "/" + msgLink);
                super.onPageFinished(view, url);
            }

            @Override
            public boolean shouldOverrideUrlLoading(WebView view, String url) {
                return super.shouldOverrideUrlLoading(view, url);
            }
        };
    }

    private WebChromeClient getChromeClient() {
        return new WebChromeClient(){

            //获取网页标题的另一种方式
            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                mTitle = title;
                setTitle(mTitle);
            }
        };
    }

    private void loadData() {
        mWebView.loadUrl(url);
    }

    @Override
    protected void onDestroy() {
        if (null != mWebView) {
            mWebView.destroy();
        }
        super.onDestroy();
    }

    @Override
    protected void onRightTitleClick() {
        //分享
    }
}

你可能感兴趣的:(Android点滴)