Fork me on GitHub

iOS与JS(二):MessageHandler(OC&Swift)

iOS与JS的相互调用除了URL拦截(iOS与JS(一):使用URL拦截的方式进行JS与OC互相调用)外,还可以使用WKWebView的中的MessageHandler来实现。

MessageHandler是什么呢?以代码来说明,比较好理解。
在OC中初始化WKWebView是,添加如下代码:
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Location"];
那么在JS中就可以使用:
window.webkit.messageHandlers.Location.postMessage(null);
JS中的Location就对应OC中的namepostMessage后的参数就是JS传给OC的参数,类型可以是 NSNumber, NSString, NSDate, NSArray, NSDictionary, and NSNull。
JS回调OC时,就回调WKScriptMessageHandler- (void)userContentController:([WKUserContentController](apple-reference-documentation://hcracoR5p2) *)userContentController didReceiveScriptMessage:([WKScriptMessage](apple-reference-documentation://hcD3KQdcJY) *)message;方法,这边的messageWKScriptMessagemessage.name就是“Location”,message.body就是postMessage后的参数。

下面看完整的🌰:

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
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47

<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf8">
<script language="javascript">
var ctuapp_share_img="www.baidu.com";

function locationClick() {
window.webkit.messageHandlers.Location.postMessage(null);
}

function shake() {
window.webkit.messageHandlers.Shake.postMessage(null);
}

function payClick(){
window.webkit.messageHandlers.Pay.postMessage({order_no:'201511120981234',channel:'wx',amount:1,subject:'粉色外套'});
}

function setLocation(location) {
alert(location)
document.getElementById("returnValue").value = location;
}

function payResult(str) {
alert(str);
document.getElementById("returnValue").value = str;
}

</script>
</head>

<body>
<h1>这是按钮调用</h1>
<input type="button" value="获取定位" onclick="locationClick()" /><br><br>
<input type="button" value="震动一下" onclick="shake()" /><br><br>
<input type="button" value="支付" onclick="payClick()" /><br><br>


<h1>这是文件上传</h1>
<input type="file" /><br><br>

<h1>这是回调结果展示区</h1>
<textarea id ="returnValue" type="value" rows="5" cols="50"></textarea>

</body>
</html>

初始化WKWebView

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
- (void)initWKWebView
{
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];

WKPreferences *preferences = [WKPreferences new];
preferences.javaScriptCanOpenWindowsAutomatically = YES;
preferences.minimumFontSize = 40.0;
configuration.preferences = preferences;

self.webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];


NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
NSURL *fileURL = [NSURL fileURLWithPath:urlStr];
[self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];

self.webView.UIDelegate = self;
[self.view addSubview:self.webView];
}

添加 MessageHandler

为了防止循环引用,结束时释放。

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
- (void)viewWillAppear:(BOOL)animated
{
[super viewWillAppear:animated];
// addScriptMessageHandler 很容易导致循环引用
// 控制器 强引用了WKWebView,WKWebView copy(强引用了)configuration, configuration copy (强引用了)userContentController
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Location"];
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Shake"];
[self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Pay"];
}

- (void)viewWillDisappear:(BOOL)animated
{
[super viewWillDisappear:animated];

[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Location"];
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Shake"];
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Pay"];
}

实现WKUIDelegate和WKScriptMessageHandler协议方法

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
#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];
}

#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
// message.body -- Allowed types are NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull.
NSLog(@"body:%@",message.body);
if ([message.name isEqualToString:@"Location"]) {
[self getLocation];
} else if ([message.name isEqualToString:@"Shake"]) {
[self shakeAction];
} else if ([message.name isEqualToString:@"Pay"]) {
[self payWithParams:message.body];
}
}

效果:

Swift的和OC类型,代码我也一起写了

代码: 90-iOSJS 中的 OCJSMessageHandlerSwiftJSMessageHandler

参考:iOS下JS与OC互相调用(三)–MessageHandler


--------------------本文结束👨‍💻感谢您的阅读--------------------
坚持原创技术分享,您的支持将鼓励我继续创作!
  • 本文标题: iOS与JS(二):MessageHandler(OC&Swift)
  • 本文作者: AndyRon
  • 发布时间: 2017年09月06日 - 00:00
  • 最后更新: 2019年09月03日 - 12:58
  • 本文链接: http://andyron.com/2017/ios-js-2.html
  • 版权声明: 本博客所有文章除特别声明外,均采用 CC BY-NC-SA 3.0 许可协议。转载请注明出处!
0%