Android JS in WebView.loadUrl()

后端 未结 2 2043
孤城傲影
孤城傲影 2021-02-02 02:30

I want to load a webpage in WebView but remove parts of the webpage. So, I created a custom WebViewClient. And, in onPageFinished(), I did some javascript to remove some eleme

2条回答
  •  礼貌的吻别
    2021-02-02 03:03

    In 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);");
    

    In MainActivity.onCreate():

    this.webView.addJavascriptInterface(new JsObject(webView, loadingView), "CallToAnAndroidFunction");
    

    In 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);               
               }
           });
        }
    }
    

    So, it was a combination of making a JavascriptInterface and making a JS function to wait for the JS calls to finish before calling the interface (with the visibility settings).

提交回复
热议问题