美文网首页Android
android WebView 注入js 几种方式

android WebView 注入js 几种方式

作者: BillZhang88 | 来源:发表于2020-04-23 15:53 被阅读0次

有时我们开发中需要将js 注入到我们本地,有可能你会说,放在Web不就可以了吗,的确,但是需求就是这样的

通过流的形式注入

 @SuppressLint("ObsoleteSdkInt")
    public void onJsLocal() {
        StringBuilder builder = new StringBuilder(getJS(this, "qqq.js"));
        if (Build.VERSION.SDK_INT <= Build.VERSION_CODES.KITKAT) {
            agentWeb.getWebCreator().getWebView() .loadUrl("javascript:" + builder.toString());
        } else {
            agentWeb.getWebCreator().getWebView().evaluateJavascript(builder.toString(), new ValueCallback<String>() {
                @Override
                public void onReceiveValue(String value) {
                    Log.i("onReceiveValue", value);
                }
            });
        } 
    }

第二种 通过文件加载

view.loadUrl("javascript:(function() { "
                                + " " //turns to red the background color
                                + " var script=document.createElement('script'); "
                                + " script.setAttribute('type','text/javascript'); "
                                + " script.setAttribute('src', 'http://192.168.12.2/assets/mathjax/jsBridge.js'); "
                                + " script.onload = function(){ "
                                + "  console.log('aaaaaaaa' ) ; "
                                + " }; "
                                + " document.getElementsByTagName('head')[0].appendChild(script); "
                                + "})()");

第三种,第二种有可能存在加载不成功的情况,我们可以拦截

 Map<String, String> map = new HashMap<>();
                                map.put("Access-Control-Allow-Origin", "*");
                                map.put("Access-Control-Allow-Headers", "Content-Type");
                                WebResourceResponse resourceResponse = new WebResourceResponse("application/javascript",
                                        "UTF-8", 200, "OK", map,
                                        getApplication().getAssets().open(JS_FILENAME));
                               

注意由于注入是一个异步的操作,所以和js交互的过程有可能存在不顺畅的问题

可以采用

view.postDelay ... 

相关文章

网友评论

    本文标题:android WebView 注入js 几种方式

    本文链接:https://www.haomeiwen.com/subject/qrdiuhtx.html