android webview 加载URL js不执行的解决方法

作为一个懒者,想做一个简单的apk,把做好的一个简单SPA 页面嵌入webview,是个不错的主意。在使用过程中发现页面的有些js 不执行,下面介绍个人遇到这问题的解决方法及相关知识的记录。

android webview 加载URL js不执行的解决方法

一个加载本地html 文件的例子:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
import android.app.Activity;
import android.os.Bundle;
import android.webkit.WebSettings;
import android.webkit.WebView;

public class AActivity extends Activity{
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// 创建WebView
		WebView webView= new WebView(this);
		// 切换到内容视图
		setContentView(webView);
		// 获取WebView配置
		WebSettings ws = webView.getSettings();
		// 启用JavaScript
		ws.setJavaScriptEnabled(true);
		 // 设置允许JS弹窗
		// ws.setJavaScriptCanOpenWindowsAutomatically(true);
		// 在运行脚本前,要有document对象,至少得load一个空白页
		webView.loadData("","text/html","UTF-8");
		// 载入assets目录下的一个页面
		webView.loadUrl("file:///android_asset/www/cow/index.html ");
		// 载入网络的一个页面
		// webView.loadUrl("http://www.baidu.com");
	}
}

让JS 在android webview 里执行很重要的两行代码是:

1
2
3
4
// 启用JavaScript
ws.setJavaScriptEnabled(true);
// 在运行脚本前,要有document对象,至少得load一个空白页
webView.loadData("","text/html","UTF-8");

这可以让基本的js 脚本运行,如果要运行alert 弹窗,就多加一行:

1
ws.setJavaScriptCanOpenWindowsAutomatically(true);

自定义出错页面:

1
2
3
4
mWebView.setWebViewClient(new WebViewClient() { 
      @Override public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
      mWebView.loadUrl("file:///android_asset/error.html");
} });

本文网址: https://pylist.com/topic/155.html 转摘请注明来源

Suggested Topics

Android webview input file 上传图片

webview 载入的网页里的 input file 点击后无法弹出窗口,是系统为了安全问题屏蔽了,可以通过重写`setWebChromeClient` 实现系统调用。...

原生 js 实现选择图片后本地预览

在web 编程里有时候会需要这样的功能,在 file 控件里选择图片后需要实时预览,而不用上传到服务器。可以用 `URL.createObjectURL()` 函数实现。...

删除确认 js confirm onclick

删除确认经常使用在删除按钮或链接上,可以防止误操作,特别是对没有恢复数据的程序。...

Leave a Comment