2019-04-12JS调用OC方法,WKwebView

我这里用的是wkwebView.
要实现js调用OC,我们首先要在html代码中预留调用OC的接口,也就是要在html中,按固定格式声明一个方法,方法的格式:

ActionName:原生中对应的方法名;parameter:回传的参数
window.webkit.messageHandlers.ActionName.postMessage('parameter');

OC 对应代码

遵守代理
创建 WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];    
self.wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight-NavigationBarHeight) configuration:config];
self.wkWebView.UIDelegate = self;
self.wkWebView.navigationDelegate = self;
[config.userContentController addScriptMessageHandler:[[BaseWKScriptDelegate alloc] initWithDelegate:self] name:@"back"];
//#pragma mark - WKScriptMessageHandler
- (void)userContentController(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
       if ([message.name isEqualToString:@"back"]) {
      [self.navigationController popViewControllerAnimated:YES];
  }
}
 - (void)dealloc{
  [[self.wkWebView configuration].userContentController removeScriptMessageHandlerForName:@"back"];
}

-(void)back{
   [kKMNotificationCenter postNotificationName:ZHENGJIANSHAUXIN object:nil];

 [self.navigationController popViewControllerAnimated:YES];
}

总的来说,要实现JS调用OC方法,重点就是三项:
1.必须在html中预留接口,格式是固定的:window.webkit.messageHandlers.ActionName.postMessage('parameter');
2.陪着WKWebViewConfiguration,并通过WKUserContentController注册html中预留的方法;
3.实现WKScriptMessageHandler协议的- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message方法。

推荐阅读更多精彩内容