webview4.4以上版本使用loadurl加载过长js文件失效问题

因为业务需要, 需要在使用Webview的时候,动态的加载js文件到页面中,之前SDK Target版本为16 , 无论JS文件多大,使用一切正常~

近期将target版本改为了19 ,发现存在js过大的时候,使用4.4以上版本执行项目,JS文件不执行。

查看源码发现在4.4版本以上内核对处理js做了区别处理:

495    @Override
496    public void loadUrl(final String url, Map<String, String> additionalHttpHeaders) {
497        // TODO: We may actually want to do some sanity checks here (like filter about://chrome).
498
499        // For backwards compatibility, apps targeting less than K will have JS URLs evaluated
500        // directly and any result of the evaluation will not replace the current page content.
501        // Matching Chrome behavior more closely; apps targetting >= K that load a JS URL will
502        // have the result of that URL replace the content of the current page.
503        final String JAVASCRIPT_SCHEME = "javascript:";
504        if (mAppTargetSdkVersion < Build.VERSION_CODES.KITKAT &&
505                url != null && url.startsWith(JAVASCRIPT_SCHEME)) {
506            mFactory.startYourEngines(true);
507            if (checkNeedsPost()) {
508                mRunQueue.addTask(new Runnable() {
509                    @Override
510                    public void run() {
511                        mAwContents.evaluateJavaScriptEvenIfNotYetNavigated(
512                                url.substring(JAVASCRIPT_SCHEME.length()));
513                    }
514                });
515            } else {
516                mAwContents.evaluateJavaScriptEvenIfNotYetNavigated(
517                        url.substring(JAVASCRIPT_SCHEME.length()));
518            }
519            return;
520        }
521
522        LoadUrlParams params = new LoadUrlParams(url);
523        if (additionalHttpHeaders != null) params.setExtraHeaders(additionalHttpHeaders);
524        loadUrlOnUiThread(params);
525    }
进一步查看,发现在4.4版本, 系统提供了:

632    public void evaluateJavaScript(String script, ValueCallback<String> resultCallback) {
633        checkThread();
634        mAwContents.evaluateJavaScript(script, resultCallback);
635    }

查看说明

Asynchronously evaluates JavaScript in the context of the currently displayed page. If non-null, |resultCallback| will be invoked with any result returned from that execution. This method must be called on the UI thread and the callback will be made on the UI thread.

Parameters
script	the JavaScript to execute.
resultCallback	A callback to be invoked when the script execution completes with the result of the execution (if any). May be null if no notificaion of the result is required.

发现该方法用于执行JavaScript 方法, 那么既然有了它,就可以不用loadurl ,so 区分版本试一下, 果然有了效果。

另外其实还有个偷懒的解决方法:因为loadurl区分版本是用的target , 那么把target改小点呗,但是版本早晚要升上来, 治标不治本。



  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值