WKWebView JS 交互
客户端中加入以下代码 可以监听JS->OC
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
[configuration.userContentController addScriptMessageHandler:self name:@"abc"];
//发送的信息仅支持字符串
window.webkit.messageHandlers.abc.postMessage("你好") ;
当在页面中调用 以上JS代码后 在 delegate 中接受到数据
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:@"abc"]) {
NSLog(@" %@",message.body);
}
}
//移除Handler
[self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"abc"];
重点
在这里的Controller 退出的时候dealloc ,并不会执行。 WKScriptMessageHandler,会有内存泄漏的Bug,
目前的解决方式 新建一个对象实现上述代理。
@interface WeakMessageHandler : NSObject <WKScriptMessageHandler>
@property (nullable, nonatomic, weak)id <WKScriptMessageHandler> delegate; //重点
-(instancetype)initWithMessageHandler:(id<WKScriptMessageHandler>) delegate ;
@end
-(instancetype)initWithMessageHandler:(id<WKScriptMessageHandler>)delegate {
if (self = [super init]) {
_delegate = delegate;
}
return self;
}
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if (self.delegate && [self.delegate respondsToSelector:@selector(userContentController:didReceiveScriptMessage:)]) {
[self.delegate userContentController:userContentController didReceiveScriptMessage:message];
}
}
即可解决内存泄漏的问题
OC->JS
[self.webView evaluateJavaScript:@"方法" completionHandler:nil]
网友评论