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改小点呗,但是版本早晚要升上来, 治标不治本。
郑重声明:本站内容如果来自互联网及其他传播媒体,其版权均属原媒体及文章作者所有。转载目的在于传递更多信息及用于网络分享,并不代表本站赞同其观点和对其真实性负责,也不构成任何其他建议。