http://www.cnblogs.com/markstray/p/5757264.html
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
self.userContentController = [[WKUserContentController alloc] init];
[self.userContentController addScriptMessageHandler:self name:@"showName"];//注册一个name为testClick的js方法
config.userContentController = self.userContentController;
self.wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 200, 375, 200) configuration:config];
self.wkWebView.UIDelegate = self;
self.wkWebView.navigationDelegate = self;
[self.view addSubview:self.wkWebView];
[self.wkWebView loadRequest:[NSURLRequest requestWithURL:url]];
-
(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
NSLog(@"%@",NSStringFromSelector(_cmd));
NSLog(@"%@",message.body);if ([message.name isEqualToString:@"showMobile"]) {
[self showMsg:@"我是下面的小红 手机号是:18870707070"];
}if ([message.name isEqualToString:@"showName"]) {
NSString *info = [NSString stringWithFormat:@"你好 %@, 很高兴见到你",message.body];
[self showMsg:info];
}if ([message.name isEqualToString:@"showSendMsg"]) {
NSArray *array = message.body;
NSString *info = [NSString stringWithFormat:@"这是我的手机号: %@, %@ !!",array.firstObject,array.lastObject];
[self showMsg:info];
}
}
// 2. native调用js
-
(IBAction)btnClick:(UIButton *)sender {
if (!self.wkWebView.loading) {
if (sender.tag == 123) {
[self.wkWebView evaluateJavaScript:@"alertMobile()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
//TODO
NSLog(@"%@ %@",response,error);
}];
}if (sender.tag == 234) { [self.wkWebView evaluateJavaScript:@"alertName('小红')" completionHandler:nil]; } if (sender.tag == 345) { [self.wkWebView evaluateJavaScript:@"alertSendMsg('18870707070','周末爬山真是件愉快的事情')" completionHandler:nil]; }
} else {
NSLog(@"the view is currently loading content");
}
}
JS端:
function clear() {
document.getElementById('mobile').innerHTML = ''
document.getElementById('name').innerHTML = ''
document.getElementById('msg').innerHTML = ''
}
//OC调用JS的方法列表
function alertMobile() {
//这里已经调用过来了 但是搞不明白为什么alert方法没有响应
//alert('我是上面的小黄 手机号是:13300001111')
document.getElementById('mobile').innerHTML = '我是上面的小黄 手机号是:13300001111'
}
function alertName(msg) {
//alert('你好 ' + msg + ', 我也很高兴见到你')
document.getElementById('name').innerHTML = '你好 ' + msg + ', 我也很高兴见到你'
}
function alertSendMsg(num,msg) {
//window.alert('这是我的手机号:' + num + ',' + msg + '!!')
document.getElementById('msg').innerHTML = '这是我的手机号:' + num + ',' + msg + '!!'
}
//JS响应方法列表
function btnClick1() {
window.webkit.messageHandlers.showMobile.postMessage(null)
}
function btnClick2() {
window.webkit.messageHandlers.showName.postMessage('xiao黄')
}
function btnClick3() {
window.webkit.messageHandlers.showSendMsg.postMessage(['13300001111', 'Go Climbing This Weekend !!!'])
}