Android WebView注入JQuery、JS脚本及执行无

2018-07-06  本文已影响0人  Goven

在项目中遇到JQuery注入后,执行无效的问题。
我们知道必须在网页加载完成后,也就是在onPageFinished()方法被调用后才能执行被注入的JS。
但是在有些手机上并不能成功执行,我的解决方案是设置一秒延迟后注入JS,成功了!why,i dont know...

WebView注入JS的封装

JSUtil.java

import android.app.Activity;
import android.webkit.ValueCallback;
import android.webkit.WebView;

import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;

public class JSUtil {

   public static JSUtil instance;
   private WebView webview;
   private String juqueryContent;
   
   public static JSUtil getInstance(WebView webView) {
       if (instance == null) {
           instance = new JSUtil(webView);
       } else {
           instance.webview = webView;
       }
       return instance;
   }

   private JSUtil(WebView webView) {
       webview = webView;
       try {
           InputStream in = webView.getContext().getAssets().open("jquery.min.js");
           byte buff[] = new byte[1024];
           ByteArrayOutputStream fromFile = new ByteArrayOutputStream();
           do {
               int numread = in.read(buff);
               if (numread <= 0) {
                   break;
               }
               fromFile.write(buff, 0, numread);
           } while (true);
           juqueryContent = fromFile.toString();
       } catch (IOException e) {
           e.printStackTrace();
       }
   }

   /**
    * 注入jquery
    */
   public void injectJquery(final InjectCallback injectCallback) {
       webview.loadUrl("javascript:" + juqueryContent);
       webview.postDelayed(new Runnable() {
           @Override
           public void run() {
               injectCallback.onSuccess();
           }
       },1000);
   }

   interface InjectCallback {
       void onSuccess();
       void onFail();
   }
   
   /**
    * 原生设置dom值
    */
   public void js_dom_setValueById(String id, String value) {
       String js = "javascript:document.getElementById('" + id + "').value = '" + value + "'";
       loadJs(js);
   }

   /**
    * 原生设置dom值
    */
   public void js_dom_setValueByName(String name, String value) {
       String js = "javascript:document.getElementsByName('" + name + "').value = '" + value + "'";
       loadJs(js);
   }

   /**
    * js原生dom点击(通过id查找)
    */
   public void js_dom_click_byId(String id) {
       String js = "javascript:document.getElementById('" + id + "').click();";
       webview.evaluateJavascript(js, null);
   }

   /**
    * js原生dom点击(通过类查找)
    */
   public void js_dom_click_byClass(String cls) {
       String js = "javascript:document.getElementsByClassName('" + cls + "').click();";
       webview.evaluateJavascript(js, null);
   }

   /**
    * jquerydom点击(通过id查找)
    */
   public void jquery_dom_click_byId(String id) {
       String js = "var newscript = document.createElement(\"script\");";
       js += "newscript.src=\"https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js\";";
       js += "document.body.appendChild(newscript);";
       js += "newscript.onload=function(){$('#" + id + "').click();};";
       webview.evaluateJavascript(js, null);
   }

   /**
    * jquery脚本执行
    */
   public void jquery_dom(String jscontent) {
       String js = "var newscript = document.createElement(\"script\");";
       js += "newscript.src=\"https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js\";";
       js += "document.body.appendChild(newscript);";
       js += "newscript.onload=function(){" + jscontent + "};";
       webview.evaluateJavascript(js, null);
   }

   /**
    * jquerydom点击(通过类查找)
    */
   public void jquery_dom_click_byClass(String cls) {
       String js = "var newscript = document.createElement(\"script\");";
       js += "newscript.src=\"https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js\";";
       js += "document.body.appendChild(newscript);";
       js += "newscript.onload=function(){$('." + cls + "').click();};";
       webview.evaluateJavascript(js, null);
   }

   /**
    * jquery设置dom值
    */
   public void jquery_dom_setValue(String id, String value) {
       String js = "var newscript = document.createElement(\"script\");";
       js += "newscript.src='https://cdn.bootcss.com/jquery/1.12.4/jquery.min.js';";
       js += "document.body.appendChild(newscript);";
       js += "newscript.onload=function(){$('#" + id + "').val('" + value + "');};";
       webview.evaluateJavascript(js, null);
   }
   
}

执行注入

webview.setWebViewClient(new WebViewClient() {
    @Override
    public boolean shouldOverrideUrlLoading(WebView view, String url) {
        LogUtil.logD("当前的url:"+url);
        view.loadUrl(url);
        return true;
    }

    @Override
    public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
        super.onReceivedError(view, errorCode, description, failingUrl);
        LogUtil.logE(errorCode + ": " + description);
        webview.loadUrl("file:///android_asset/404.html");
    }

    @Override
    public void onPageStarted(WebView view, String url, Bitmap favicon) {
        super.onPageStarted(view, url, favicon);
        LogUtil.logD("开始加载网页:" + url);
        if (!dialog.isShowing()) {
            dialog.show();
        }
    }

    @Override
    public void onPageFinished(WebView view, final String url) {
        super.onPageFinished(view, url);
        dialog.dismiss();
        LogUtil.logD("加载完成 URL:" + url);
        webview.postDelayed(new Runnable() {
            @Override
            public void run() {
                JSUtil.getInstance(webview).injectJquery(new JSUtil.InjectCallback() {
                    @Override
                    public void onSuccess() {
                        LogUtil.logD("执行登录:点击首页登录");
                        webview.evaluateJavascript("var link=$('#nav-logobar-greeting').attr('href');if(link){window.location=link;}else{$('#gwm-SignIn-button').click();}", null);
                    }

                    @Override
                    public void onFail() {
                    }
                });
            }
        }, 1000);
    }
});

注意上面的onPageFinished方法中延迟操作,如果不加这个延迟,webview.evaluateJavascript根本无法执行(找不到“$定义”)

上一篇下一篇

猜你喜欢

热点阅读