11

我已经尝试过在 WebView 中使用 JavaScriptInterface。但它不起作用。如何从 XWalkView 获取 HTML 内容?

通过这种方式,我可以从 WebView 获取 HTML:

    public class MainActivity extends AppCompatActivity {

    WebView myWebView;

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

        myWebView = (WebView) findViewById(R.id.webView);
        WebSettings webSettings = myWebView.getSettings();

        webSettings.setJavaScriptEnabled(true);

        myWebView.loadUrl("http://joerichard.net/api/test/generate.htm");
        myWebView.getSettings().setJavaScriptEnabled(true);
        myWebView.addJavascriptInterface(new MyJavaScriptInterface(this), "HtmlViewer");

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

    }

    class MyJavaScriptInterface {

        private Context ctx;

        MyJavaScriptInterface(Context ctx) {
            this.ctx = ctx;
        }

        public void showHTML(String html) {
            Document doc = Jsoup.parse(html);
        }

    }

}

我对 XWalkView 进行了同样的尝试,但没有成功。如何从 XWalkView 获取 HTML 源代码?

4

1 回答 1

4

添加 JavaScript 接口:

 webview.addJavascriptInterface(new test(this),"bla");

设置客户端

  webview.setResourceClient(new XWalkResourceClient(webview) {

                @Override
                public void onProgressChanged(XWalkView view, int progressInPercent) {
                    super.onProgressChanged(view, progressInPercent);
                    pbLoading.setProgress(progressInPercent);
                }

                @Override
                public void onLoadFinished(XWalkView view, String url) {
                    super.onLoadFinished(view, url);
                    webview.load("javascript:window.bla.showHTML" +
                            "('<html>'+document.getElementsByTagName('html')[0].innerHTML+'</html>');"
                            ,null);
                }
            });

实现html函数

class test{
        private Context ctx;

        test(Context ctx) {
            this.ctx = ctx;
        }
         @JavascriptInterface
        public void showHTML(String html) {
            new AlertDialog.Builder(ctx).setTitle("HTML").setMessage(html)
                    .setPositiveButton(android.R.string.ok, null).setCancelable(false).create().show();
        }

    }
于 2016-08-27T12:14:24.220 回答