我想在WebView中加载一个网页,但删除部分网页.所以,我创建了一个自定义WebViewClient.并且,在onPageFinished()中,我做了一些
javascript来删除一些元素.然后,我使WebView可见.
但是,当我运行它时,它将视图设置为可见,然后我看到要删除的元素.就好像JS在后台运行非常慢.它会创建一个糟糕的观看体验,因为它会闪烁整个页面,然后闪烁所需的部分页面.
这是我的onPageFinished()
@Override public void onPageFinished(WebView view,String url) { view.loadUrl("javascript:" + "document.getElementsByClassName('header')[0].style.display='none';" + "document.getElementById('section_0').style.display='none';" + "document.getElementById('page-actions').style.display='none';" + "document.getElementsByClassName('languageSelector')[0].style.display='none';" + "document.getElementById('mw-mf-last-modified').style.display='none';" + "document.getElementById('footer').style.display='none';"); loadingView.setVisibility(View.INVISIBLE); view.setVisibility(View.VISIBLE); }
有想法该怎么解决这个吗?
解决方法
在onPageFinished()中:
view.loadUrl("javascript:" + "var FunctionOne = function () {" + " var r = $.Deferred();" + " try{document.getElementsByClassName('header')[0].style.display='none';}catch(e){}" + " try{document.getElementById('section_0').style.display='none';}catch(e){}" + " try{document.getElementById('page-actions').style.display='none';}catch(e){}" + " try{document.getElementsByClassName('languageSelector')[0].style.display='none';}catch(e){}" + " try{document.getElementById('mw-mf-last-modified').style.display='none';}catch(e){}" + " try{document.getElementById('footer').style.display='none';}catch(e){}" + " setTimeout(function () {" + " r.resolve();" + " },2500);" + " return r;" + "};" + "var FunctionTwo = function () {" + " window.CallToAnAndroidFunction.setVisible();" + "};" + "FunctionOne().done(FunctionTwo);");
在MainActivity.onCreate()中:
this.webView.addJavascriptInterface(new JsObject(webView,loadingView),"CallToAnAndroidFunction");
在MainActivity()中:
public class JsObject { private View loadingView; private View view; JsObject(View view,View loadingView){this.view = view;this.loadingView = loadingView;} @JavascriptInterface public void setVisible(){ runOnUiThread(new Runnable() { @Override public void run() { view.setVisibility(View.VISIBLE); loadingView.setVisibility(View.INVISIBLE); } }); } }
因此,它是一个组合JavascriptInterface和制作JS函数来等待JS调用完成之后调用接口(具有可见性设置).