标签:tps uiwebview test move rem use 逻辑 代理 content
本篇主要讲的是UIWebView和JS的交互,UIWebView和JS交互的详解https://www.cnblogs.com/llhlj/p/6429431.html
[webView evaluateJavaScript:@"我是JS" completionHandler:^(id _Nullable response, NSError * _Nullable error) { }];
该方法为异步执行
当JS端想传一些数据给iOS.那它们会调用下方方法来发送.
window.webkit.messageHandlers.<对象名>.postMessage(<数据>)
上方代码在JS端写会报错,导致页面后面业务不执行.可使用try-catch
执行.
那么在OC中的处理方法如下.它是WKScriptMessageHandler的代理方法.name和上方JS中的对象名相对应.
- (void)addScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name;
具体添加如下
1.设置addScriptMessageHandler的代理和名称
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init]; WKUserContentController *userContentController = [[WKUserContentController alloc] init]; [userContentController addScriptMessageHandler:self name:@"test"]; configuration.userContentController = userContentController; // WKPreferences *preferences = [WKPreferences new]; preferences.javaScriptCanOpenWindowsAutomatically = YES; // preferences.minimumFontSize = 40.0; configuration.preferences = preferences; _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT64) configuration:configuration];
2.WKScriptMessageHandler协议方法
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message { //JS调用OC方法 //message.boby就是JS里传过来的参数 NSLog(@"body:%@",message.body); if ([message.name isEqualToString:@"test"]) { //具体逻辑 [self sendMessage:message.body]; } }
3.销毁
- (void)dealloc { ... [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"对象名"]; ... }
标签:tps uiwebview test move rem use 逻辑 代理 content
原文地址:https://www.cnblogs.com/llhlj/p/9144110.html