最近做app加载assets里面的网页并执行网页的js代码时候,发现部分机型可以,部分却报错,报错大致如下
Uncaught ReferenceError: $ is not defined,或者is null,只会经过排查,传参不为空。后来才发现是页面还没加载完毕,webview就试图执行js函数导致的!
解决办法:为webview设置mWebView.setWebViewClient(new MyWebViewClient());
然后在WebViewClient 的onPageFinished调用js. mWebView.loadUrl("javascript:initNumber('"+str+"')");
private class MyWebViewClient extends WebViewClient {
@Override
public boolean shouldOverrideUrlLoading(WebView view, String url) {
// TODO Auto-generated method stub
return super.shouldOverrideUrlLoading(view, url);
}
public void onPageStarted(WebView view, String url, Bitmap favicon) {
super.onPageStarted(view, url, favicon);
// if (url.equals("http://www.baidu.com/")) {
// mWebView.stopLoading();
// }
}
@Override
public void onPageFinished(WebView view, String url) {
// TODO Auto-generated method stub
super.onPageFinished(view, url);
if (pNumber != null &&pType!=null) {
mWebView.loadUrl("javascript:initNumber('"+str+"')");
} else {
}
}