先:WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler

   // 创建一个webiview的配置项

        WKWebViewConfiguration *configuretion = [[WKWebViewConfiguration alloc] init];

         // Webview的偏好设置

         //.WKPreferences()

         // 设置偏好设置

         configuretion.preferences = [[WKPreferences alloc]init];

         configuretion.preferences.minimumFontSize = ;

         configuretion.preferences.javaScriptEnabled = true;

         configuretion.processPool = [[WKProcessPool alloc]init];

         // 通过js与webview内容交互配置

         configuretion.userContentController = [[WKUserContentController alloc] init];

         [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;

         //OC注册供JS调用的方法

         [ configuretion.userContentController addScriptMessageHandler:self name:@"ABC"];

         // 默认是不能通过JS自动打开窗口的,必须通过用户交互才能打开

         configuretion.preferences.javaScriptCanOpenWindowsAutomatically = NO;

         _wkwebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuretion];//self.view.bounds

         [_wkwebView goBack];

         [_wkwebView goForward];

         _wkwebView.navigationDelegate = self;

         _wkwebView.UIDelegate = self;

         NSURL *url = [NSURL URLWithString:urlStr];  //测试本地H5

         NSURLRequest *request = [NSURLRequest requestWithURL:url];

         [_wkwebView loadRequest:request];

再:

 -(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{

     // userContentController 注册message的WKUserContentController;
// message:js传过来的数据
// id body:消息携带的信息 Allowed types are NSNumber, NSString, NSDate, NSArray, NSDictionary, and NSNull.
// NSString *name;//消息的名字 如aaa
//message.name js发送的方法名称 if([message.name isEqualToString:@"ABC"]){ NSString * body = [message.body objectForKey:@"body"]; //在这里写oc 实现协议的native方法 } }
 前端h5代码:前端需要用 window.webkit.messageHandlers.注册的方法名.postMessage({body:传输的数据} 来给native发送消息

 例如:

 function secondClick() {

     window.webkit.messageHandlers.aaa.postMessage({body: 'call js alert in js'});

 }

 **重要 如果注册了方法    [userContentController addScriptMessageHandler:self  name:@“aaa"];

 会导致hangler一直被引用 导致不走Delloc web页面无法释放 所以要在-(void)viewDidDisappear:(BOOL)animated中将messageHandler移除

     [userContentController removeScriptMessageHandlerForName:@“aaa"]; 关闭web页时会释放内存。
05-11 15:51