webview4.4以上版本使用loadurl載入過長js檔案失效問題
阿新 • • 發佈:2019-02-10
因為業務需要, 需要在使用Webview的時候,動態的載入js檔案到頁面中,之前SDK Target版本為16 , 無論JS檔案多大,使用一切正常~
近期將target版本改為了19 ,發現存在js過大的時候,使用4.4以上版本執行專案,JS檔案不執行。
檢視原始碼發現在4.4版本以上核心對處理js做了區別處理:
進一步檢視,發現在4.4版本, 系統提供了: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 }
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改小點唄,但是版本早晚要升上來, 治標不治本。