本文介绍如果使用WKWebView
的WKScriptMessageHandler
实现iOS
与JS
交互。WKWebView
是Apple
在iOS8推出的Webkit
框架中的负责网页的渲染与展示的类,相比UIWebView
速度更快,占用内存更少,支持更多的HTML
特性。WKScriptMessageHandler
是WebKit
提供的一种在WKWebView
上进行JS
消息控制的协议。
一、iOS调用JS:
iOS调用JS方式是通过WKWebView的
-evaluateJavaScript:completionHandler:
方法来实现的。
二、JS调用iOS
-
实现逻辑:点击JS的登录按钮,JS将登录成功后的token数据传递给iOS,iOS将收到的数据展示出来。
- JS代码:
//! 登录按钮
<button onclick = "login()" style = "font-size: 18px;">登录</button>
//! 登录
function login() {
var token = "js_tokenString";
var action = "loginSucceed";
window.webkit.messageHandlers.jsToOc.postMessage(action, token);
}
- iOS代码:
//! 第一步:导入WebKit框架头文件
#import <WebKit/WebKit.h>
//! 第二步:WKWebViewWKScriptMessageHandlerController遵守WKScriptMessageHandler协议
@interface WKWebViewWKScriptMessageHandlerController () <WKScriptMessageHandler>
//! 第三步:为userContentController添加ScriptMessageHandler,并指明name
WKUserContentController *userContentController = [[WKUserContentController alloc] init];
[userContentController addScriptMessageHandler:self name:@"jsToOc"];
//! 第四步:使用添加了ScriptMessageHandler的userContentController配置configuration
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
configuration.userContentController = userContentController;
//! 第五步:使用configuration对象初始化webView
_webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuration];
//! 第六步:WKWebView收到ScriptMessage时回调此方法
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name caseInsensitiveCompare:@"jsToOc"] == NSOrderedSame) {
[WKWebViewWKScriptMessageHandlerController showAlertWithTitle:message.name message:message.body cancelHandler:nil];
}
}
- 实现原理:
1、JS与iOS约定好jsToOc
方法,用作JS在调用iOS时的方法;
2、iOS使用WKUserContentController
的-addScriptMessageHandler:name:
方法监听name
为jsToOc
的消息;
3、JS通过window.webkit.messageHandlers.jsToOc.postMessage()
的方式对jsToOc
方法发送消息;
4、iOS在-userContentController:didReceiveScriptMessage:
方法中读取name
为jsToOc
的消息数据message.body
。
注意:
[userContentController addScriptMessageHandler:self name:@"jsToOc"]
会引起循环引用问题。一般来说,在合适的时机removeScriptMessageHandler
可以解决此问题。比如:在-viewWillAppear:方法中
执行add
操作,在-viewWillDisappear:
方法中执行remove
操作。如下:
- (void)viewWillAppear:(BOOL)animated {
[super viewWillAppear:animated];
[_webView.configuration.userContentController addScriptMessageHandler:self name:@"jsToOc"];
}
- (void)viewWillDisappear:(BOOL)animated {
[super viewWillDisappear:animated];
[_webView.configuration.userContentController removeScriptMessageHandlerForName:@"jsToOc"];
}