将需要的js、css资源导入创建好的bundle下,如上图
WKWebView *webView = [[WKWebView alloc]initWithFrame:frame]]
这个filePaths 就是需要加载的 js、css文件在本地的路径,是个数组,因为可能需要加载本地的多个js、css文件, 如果需要加载的js、css文件较多,可以让后台传给你对应js、css文件的路径,注意传的路径要跟导入本地的资源路径一致,否则会加载失败。
//路径path
NSArray *pathArray = dict[@"filePath"]
if (pathArray) {
NSError *error
//获取网络的HTML
NSString * online_HTML = [NSString stringWithContentsOfURL:[NSURL URLWithString:url] encoding:NSUTF8StringEncoding error:&error]
if(!error) {
//以分割
NSArray * array_HTML = [online_HTML componentsSeparatedByString:@"</head>"]
NSMutableString *header_HTML = [[NSMutableString alloc]initWithString:array_HTML.firstObject]
for (NSString *path in pathArray) {
//注意这里的hightcharts.bundle,更改成你本地的bundle名
NSString *filePath = [[NSBundle mainBundle] pathForResource:[NSString stringWithFormat:@"hightcharts.bundle/%@",path] ofType:nil]
if ([filePath hasSuffix:@"js"]) {
[header_HTML appendFormat:@"<script src=\"%@\"><\script>",filePath]
}else if ([filePath hasSuffix:@"css"]){
[header_HTML appendFormat:@"<link rel=\"stylesheet\"
[_webView loadHTMLString:header_HTML baseURL:[[NSBundle mainBundle] bundleURL]]
}
}
第一步:将资源拷贝到assets目录第二步:给需要注入的资源文件在url上做一个标志,当然,你也可以不做,只要你在安卓端可以判断出来即可。
<link rel="stylesheet" href="[inject]public/css/bootstrap.min.css" type="text/css" media="screen" title="no title" charset="utf-8">
<link rel="stylesheet" href="[inject]public/css/bootstrap-theme.min.css" type="text/css" media="screen" title="no title" charset="utf-8">
<script type="text/javascript" src="[inject]public/js/zipto/1.1.6/zepto.min.js"></script>
<script type="text/javascript" src="[inject]public/js/modules/md5.min.js"></script>
第三步:拦截将要注入的文件,读取本地文件即可。
webview.setWebViewClient(new WebViewClient() {
@Override
public WebResourceResponse shouldInterceptRequest(WebView view, String url) {
//System.out.println("WebResourceResponse::"+url)
if(url.contains("[inject]")){
String localPath = url.replaceFirst("^http.*inject\\]","")
System.out.println("LocalPath::"+localPath)
try {
InputStream is = getApplicationContext().getAssets().open(localPath)
return new WebResourceResponse("text/javascript", "UTF-8", is)
} catch (Exception e) {
e.printStackTrace()
return super.shouldInterceptRequest(view, url)
}
} else {
return super.shouldInterceptRequest(view, url)
}
}
})