我试过使用JavaScriptInterface在WebView中做过。但它没有用。如何从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源代码?
答案 0 :(得分:3)
添加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();
}
}