- (void)addScriptMessageHandler:(id <WKScriptMessageHandler>)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 <WKScriptMessageHandler>)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);
<!DOCTYPE html>
<html>
<head>
<title>webView</title>
<style>
button {
font-size: 30px;
width: 250px;
height: 50px;
display: block;
margin-top: 5px;
}
</style>
<script type="text/javascript">
function useCamera() {
window.webkit.messageHandlers.openCamera.postMessage(null);
}
function useVideo(vedio) {
var obj = {"name":"God", "Author":"Jhon Trank"};
window.webkit.messageHandlers.playVideo.postMessage(obj);
}
</script>
</head>
<body>
<button onclick="openCamera()" id="openCameraButton">openCamera</button>
<button onclick="playVideo()" id="playVideoButton">playVideo</button>
</body>
</html>
WKScriptMessageHandler这个协议的代理方法
js通过messageHandlers调用方法,传递参数。在这个代理里,都可以获取到。
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:@"openCamera"]) {
NSLog(@"%@ -- %@", message.name, message.body);//openCamera -- <null>
}else if([message.name isEqualToString:@"playVideo"]) {
NSLog(@"%@ -- %@", message.name, message.body);//playVideo -- {Author = "Jhon Trank";name = God;}
}
}
网友评论