如何将结果从JavascriptInterface传输到OnCreate?

时间:2018-10-22 14:25:33

标签: android webview

尝试获取在Webview中加载的页面的html代码。一切都很好,但是我不明白如何将代码从JavascriptInterface转移到OnCreate。请不要踢太多,我是新来的。

LineString

1 个答案:

答案 0 :(得分:0)

为您的活动添加成员变量,代码如下:

public class MainActivity extends AppCompatActivity{

   String TAG = "111232312312";
   String mHtmlCode;
   MyJavaScriptInterface MJInterface = new MyJavaScriptInterface();

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

        final WebView simpleWebView=(WebView) findViewById(R.id.wvBrowser);
        simpleWebView.getSettings().setJavaScriptEnabled(true);
        simpleWebView.getSettings().setUserAgentString("Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/70.0.3538.67 Safari/537.36");
        simpleWebView.setWebViewClient(new WebViewClient() {
            public void onPageFinished(WebView view, String url) {
                // do your stuff here
                String cookies = CookieManager.getInstance().getCookie(url);
                Log.d(TAG, url+ " All the cookies in a string:" + cookies);
                simpleWebView.loadUrl("javascript:window.HTMLOUT.showHTML('<head>'+document.getElementsByTagName('html')[0].innerHTML+'</head>');");
                mHtmlCode = MJInterface.htmlString;
                Log.d(TAG, "[[[" + MJInterface.htmlString + "]]]");
            }
            @Override
            public void onReceivedError(WebView view, WebResourceRequest request, WebResourceError error) {
                Log.d(TAG, "ERROR");
                super.onReceivedError(view, request, error);
            }
        });
        simpleWebView.addJavascriptInterface(MJInterface, "HTMLOUT");
        simpleWebView.loadUrl("https://www.youtube.com");
    }

    class MyJavaScriptInterface {
        public String htmlString = "";
        @JavascriptInterface
        public void showHTML(String html) {
            htmlString = html;
            Pattern p = Pattern.compile("data-sitekey=(.*?)\"><");
            Matcher m = p.matcher(htmlString);
            while(m.find()) {
                Log.d(TAG,m.group(0));
                Log.d(TAG,m.group(1));
            }
        }
    }
}