WKwebView与JS交互(h5主动)

先:WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler

 1   // 创建一个webiview的配置项
 2 
 3        WKWebViewConfiguration *configuretion = [[WKWebViewConfiguration alloc] init];
 4 
 5         // Webview的偏好设置
 6 
 7         //.WKPreferences()
 8 
 9         // 设置偏好设置
10 
11         configuretion.preferences = [[WKPreferences alloc]init];
12 
13         configuretion.preferences.minimumFontSize = 10;
14 
15         configuretion.preferences.javaScriptEnabled = true;
16 
17         configuretion.processPool = [[WKProcessPool alloc]init];
18 
19         // 通过js与webview内容交互配置
20 
21         configuretion.userContentController = [[WKUserContentController alloc] init];
22 
23         [UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
24 
25         //OC注册供JS调用的方法
26 
27         [ configuretion.userContentController addScriptMessageHandler:self name:@"ABC"];
28 
29         // 默认是不能通过JS自动打开窗口的,必须通过用户交互才能打开
30 
31         configuretion.preferences.javaScriptCanOpenWindowsAutomatically = NO;
32 
33         _wkwebView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:configuretion];//self.view.bounds
34 
35         [_wkwebView goBack];
36 
37         [_wkwebView goForward];
38 
39         _wkwebView.navigationDelegate = self;
40 
41         _wkwebView.UIDelegate = self;
42 
43         NSURL *url = [NSURL URLWithString:urlStr];  //测试本地H5
44 
45         NSURLRequest *request = [NSURLRequest requestWithURL:url];
46 
47         [_wkwebView loadRequest:request];

再:

 1 -(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
 2     
 3     // userContentController 注册message的WKUserContentController;
 4     // message:js传过来的数据
 5     // id body:消息携带的信息 Allowed types are NSNumber, NSString, NSDate, NSArray, NSDictionary, and NSNull.
 6     // NSString *name;//消息的名字 如aaa
 7     //message.name  js发送的方法名称
 8         
 9     if([message.name  isEqualToString:@"ABC"]){
10             
11     NSString * body = [message.body objectForKey:@"body"];
12                                
13                                //在这里写oc 实现协议的native方法
14        
15         
16     }
17     
18     
19     
20 }
 1 前端h5代码:前端需要用 window.webkit.messageHandlers.注册的方法名.postMessage({body:传输的数据} 来给native发送消息
 2 
 3 例如:
 4 
 5 function secondClick() {
 6 
 7     window.webkit.messageHandlers.aaa.postMessage({body: 'call js alert in js'});
 8 
 9 }
10 
11 
12 
13 **重要 如果注册了方法    [userContentController addScriptMessageHandler:self  name:@“aaa"];
14 
15 会导致hangler一直被引用 导致不走Delloc web页面无法释放 所以要在-(void)viewDidDisappear:(BOOL)animated中将messageHandler移除
16 
17     [userContentController removeScriptMessageHandlerForName:@“aaa"]; 关闭web页时会释放内存。
原文地址:https://www.cnblogs.com/-yun/p/6016516.html