一、什么是MessageHandler
MessageHandler是WKWebView用来处理原生与JS交互的消息处理机制。也即是说:JS要想调用iOS原生的方法,可以采用MessageHandler。
二、怎么注入js的方法
WKWebView在创建的时候有一个属性:WKWebViewConfiguration,这个configuration有个WKUserContentController类型的属性:userContentController。在userContentController中我们是通过:addScriptMessageHandler:name方法来注入js的方法的。
- (void)addScriptMessageHandler:(id<WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name;
参数:scriptMessageHandler是userContentController的代理对象;
参数:name是js方法名。
可以多次调用此方法或者说注入多个MessageHandle来注入多个js的方法。
三、js如何调用OC的方法
WKWebView通过实现WKScriptMessageHandler代理协议来调用OC的方法。此协议只有一个代理方法。
- (void)userContentController:(nonnull WKUserContentController *)userContentController didReceiveScriptMessage:(nonnull WKScriptMessage *)message
API文档是这么说的:
/*! @abstract Invoked when a script message is received from a webpage.
@param userContentController The user content controller invoking the
delegate method.
@param message The script message received.
*/
参数message有个属性:
1、body: 可以理解为js传过来的参数。可以是字典,字符串等,客户端接收到之后用来调oc的方法。
@discussion Allowed types are NSNumber, NSString, NSDate, NSArray,
NSDictionary, and NSNull.
2、name:可以理解为js的方法名称。客户端接收到后针对不同的消息进行判断逻辑处理。
四、demo
.h
#import <UIKit/UIKit.h>
#import <WebKit/WebKit.h>
NS_ASSUME_NONNULL_BEGIN
@interface STBaseWebViewController : UIViewController
@property (nonatomic, copy) NSString *urlStr;
@property (nonatomic, strong) NSArray *jsArr;
@end
NS_ASSUME_NONNULL_END
.m
#import "STBaseWebViewController.h"
@interface STBaseWebViewController ()<WKScriptMessageHandler>
@property (nonatomic, strong) WKWebView *webView;
@property (nonatomic, strong) NSArray *jsFuncArr;
@end
@implementation STBaseWebViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
[self.view addSubview:self.webView];
[self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:self.urlStr]]];
}
- (WKWebView *)webView
{
if (_webView) {
WKWebViewConfiguration *configuration = [WKWebViewConfiguration new];
WKPreferences *preferences = [WKPreferences new];
preferences.minimumFontSize = 10;
preferences.javaScriptCanOpenWindowsAutomatically = YES;
configuration.preferences = preferences;
configuration.userContentController = [WKUserContentController new];
// injection JS function
for (NSString *funcStr in self.jsFuncArr) {
[configuration.userContentController addScriptMessageHandler:self name:funcStr];
}
_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 44, self.view.bounds.size.width, self.view.bounds.size.height - 44) configuration:configuration];
}
return _webView;
}
- (NSArray *)jsFuncArr {
if (!_jsFuncArr) {
_jsFuncArr = [NSArray array];
}
return _jsFuncArr;
}
#pragma mark - WKScriptMessageHandler
// js call oc
- (void)userContentController:(nonnull WKUserContentController *)userContentController didReceiveScriptMessage:(nonnull WKScriptMessage *)message {
// name: function name
// body: js->oc parameters such as Dictionary...
if ([message.name isEqualToString:@"takePhoto"]) {
// call oc methord
if ([message.body isKindOfClass:[NSDictionary class]]) {
NSString *title = message.body[@"title"];
NSString *content = message.body[@"contentt"];
NSLog(@"js pass value to oc:[title:%@ content:%@]",title,content);
// ...
}
} else if ([message.name isEqualToString:@"otherFunction"]){ // ... otherFunction
} else {
// oc call js
NSString *title = @"OC调用JS";
NSString *content = @"执行evaluateJavaScript方法,在completionHandler里面处理回调";
NSString *jsFunc = [NSString stringWithFormat:@"jsShare('%@','%@')",title,content];
[self.webView evaluateJavaScript:jsFunc completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"result--->%@",result);
}];
}
}
- (void)takePhoto {
NSLog(@"take photo...");
}
@end