- (void)addScriptMessageHandler:(id )scriptMessageHandler name:(NSString *)name;
//WKWebView initial
WKWebView *webView = [[WKWebView alloc] initWithFrame:self.view.bounds];
[self.view addSubview:_webView];
NSString *path = [[NSBundle mainBundle] pathForResource:@"WebView" ofType:@"html"];
NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
[webView loadRequest:request];
//- (void)addScriptMessageHandler:(id )scriptMessageHandler name:(NSString *)name;
//name表示添加的js方法名
[webView.configuration.userContentController addScriptMessageHandler:self name:@"openCamera"];
[webView.configuration.userContentController addScriptMessageHandler:self name:@"playVideo"];
window.webkit.messageHandlers.注册的方法名.postMessage(parameters);
webView
WKScriptMessageHandler这个协议的代理方法
js通过messageHandlers调用方法,传递参数。在这个代理里,都可以获取到。
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:@"openCamera"]) {
NSLog(@"%@ -- %@", message.name, message.body);//openCamera --
}else if([message.name isEqualToString:@"playVideo"]) {
NSLog(@"%@ -- %@", message.name, message.body);//playVideo -- {Author = "Jhon Trank";name = God;}
}
}