android WebView 注入js 几种方式

2020-08-16 16:09:30

参考地址 android WebView 注入js 几种方式

有时我们开发中需要将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 ...


  • 2020-04-01 10:15:11

    vue-cli3.0中vue.config.js的基本配置(去除esLint提示和解决build后静态文件路径报错)

    vue-cli是开发vue项目必不可少的脚手架工具,3.0版本之前的目录结构是由config目录的,关于webpack配置的文件都放在该目录里面,而3.0版本之后做了一个大更新,webpack相关的默认配置都帮你集成到webpack的npm 包里面去了,官方提供的一种修改配置的方式就是开发者自己在项目的根目录(与src同层级的目录)下建立一个vue.config.js的文件,然后去覆盖自定义的配置,达到你想要的效果,下面写一个基本的默认配置

  • 2020-04-01 10:21:20

    Vue extend $mount 构造器详解

    本节介绍两个 Vue.js 内置但却不常用的 API——extend 和 $mount,它们经常一起使用。不常用,是因为在业务开发中,基本没有它们的用武之地,但在独立组件开发时,在一些特定的场景它们是至关重要的。

  • 2020-04-01 15:36:52

    CSS3中的transition属性详解

    transition: property duration timing-function delay transition属性是个复合属性,她包括以下几个子属性: transition-property :规定设置过渡效果的css属性名称 transition-duration :规定完成过渡效果需要多少秒或毫秒 transition-timing-function :指定过渡函数,规定速度效果的速度曲线 transition-delay :指定开始出现的延迟时间