序言
由于UIWebview即将废弃,相比较于WKWebview,通过测试即可发现UIWebview占用更多内存,且内存很夸张。WKWebView网页加载速度也有提升,但是并不像内存那样提升那么多。下面列举一些其它的优势:
- 更多的支持HTML5的特性
- 官方宣称的高达60fps的滚动刷新率以及内置手势
- Safari相同的JavaScript引擎
- 将UIWebViewDelegate与UIWebView拆分成了14类与3个协议(官方文档说明)
- 另外用的比较多的,增加加载进度属性:estimatedProgress
本文主要以WKWebview交互为主介绍。分为三部分:1、JS与OC交互 2、js事件注入 3、修改js系统或者自定义方法实现
一、JS与OC交互
-
MessageHandle交互通过
- 1.1 创建WKWebViewConfiguration对象,配置各个API对应的MessageHandler。
#pragma mark -- 初始化
- (void)initView{
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
WKPreferences *preference = [WKPreferences new];
preference.javaScriptCanOpenWindowsAutomatically = YES;
preference.minimumFontSize = 40.0;
configuration.preferences = preference;
// WKWebView
CGRect webViewFrame = CGRectMake(0, 180, self.view.bounds.size.width, self.view.bounds.size.height * 0.8);
self.webView = [[WKWebView alloc] initWithFrame:webViewFrame configuration:configuration];
NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
NSURL *fileURL = [NSURL fileURLWithPath:urlStr];
[self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
self.webView.navigationDelegate = self;
self.webView.UIDelegate = self;
[self.view addSubview:self.webView];
[self addJSActionByOC];
}
- 配置MessageHandler
需要注意的是addScriptMessageHandler很容易引起循环引用,导致控制器无法被释放,所以需要移除MessageHandler
#pragma mark -- 生命周期
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
// addScriptMessageHandler 很容易导致循环引用
// 控制器 强引用了WKWebView,WKWebView copy(强引用了)configuration, configuration copy (强引用了)userContentController
// userContentController 强引用了 self (控制器)
// js调用oc方之前要进行注册
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Location"];
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Share"];
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Color"];
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"GoBack"];
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"ocZRAction"];
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"asyncAction"];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
// 因此这里要记得移除handlers
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Location"];
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Share"];
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Color"];
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"GoBack"];
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"ocZRAction"];
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"asyncAction"];
}
- 1.2 实现协议方法
这实现三个协议<WKNavigationDelegate,WKUIDelegate, WKScriptMessageHandler>
WKUIDelegate
是因为我在JS中弹出了alert 。 -
js代码
<input type="button" value="oc拦截alert提示" onclick="colorClick()" />
function colorClick() {
alert('55555')
}
-
oc代码,js alert(),会触发WKUIDelegate代理中的webView:runJavaScriptAlertPanelWithMessage:方法执行
#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:message preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
completionHandler();
}]];
[self presentViewController:alert animated:YES completion:nil];
}
WKScriptMessageHandler是因为我们要处理JS调用OC方法的请求。
WKScriptMessage有两个关键属性name 和 body。
因为我们给每一个OC 方法取了一个name,那么我们就可以根据name 来区分执行不同的方法。body 中存着JS 要给OC 传的参数。
-
js代码
<input type="button" value="调用oc方法传递事件" onclick="goBack()" />
function goBack() {
window.webkit.messageHandlers.asyncAction.postMessage("传递数据");
}
-
oc代码
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
// message.body -- Allowed types are NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull.
if ([message.name isEqualToString:@"Location"]) {
} else if ([message.name isEqualToString:@"Share"]) {
} else if ([message.name isEqualToString:@"Color"]) {
}else if ([message.name isEqualToString:@"GoBack"]) {
}else if ([message.name isEqualToString:@"asyncAction"]) {
NSLog(@"假死页面回调事件");
}else if ([message.name isEqualToString:@"ocZRAction"]){
NSLog(@"oc注入方法,调用oc事件 message = %@",message.body);
UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:@"调用成功" preferredStyle:UIAlertControllerStyleAlert];
[alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
}]];
[self presentViewController:alert animated:YES completion:nil];
}
}
二、JS事件注入
-
js代码
ocAddAction方法在js文件中并没有定义
<input type="button" value="oc注入js事件,调用oc" onclick="ocAddAction()" />
-
OC注入代码
实现WKNavigationDelegate协议方法,执行之后会在WKScriptMessageHandler代理方法中拦截到ocZRAction
#pragma mark - WKNavigationDelegate
///加载完成网页的时候才开始注入JS代码,要不然还没加载完时就可以点击了,就不能调用我们的代码了!
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
NSString *jsCode = @"function ocAddAction(a,b,c){\
window.webkit.messageHandlers.ocZRAction.postMessage('js注入')\
}";
[self.webView evaluateJavaScript:jsCode completionHandler:^(id _Nullable obj, NSError * _Nullable error) {
}];
}
三、动态修改JS系统函数或者自定义函数实现
-
oc代码
动态修改alert系统函数的实现,当js中调用alert函数时,触发的是我们自定义方法
#pragma mark -- 通过js注入,修改js内部函数或者系统函数内部实现
- (void)addJSActionByOC{
NSString *jsCode = @"alert = (function (oriAlertFunc){ \
return function(task)\
{\
window.webkit.messageHandlers.ocZRAction.postMessage(task);\
oriAlertFunc.call(alert,task);\
}\
})(alert);";
//injected the method when H5 starts to create the DOM tree
[self.webView.configuration.userContentController addUserScript:[[WKUserScript alloc] initWithSource:jsCode injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES]];
}
-
js代码
<input type="button" value="获取定位" onclick="locationClick()" />
function locationClick() {
alert('4444')
}