印言

最近接到一个需求:监听网页的按钮的点击事情,而且网页不是咱们招待一声对方就能改的。那么一切的故事从这里开始了。正文部分首要环绕监听网页的事情为主线。

正文

WKWebView加载本地html页面, 搭建UI做准备工作。

NSString *path = [[NSBundle mainBundle] pathForResource:@"oc&js.html" ofType:nil];
[_wkWeb loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]]];

html和oc各创建两个按钮,俩个按钮别离测验无参数和有参数音讯的传递。

<h2>是H5按钮</h2>
<button type="button" onclick="js2oc1()">js调用oc的按钮1</button>
<button type="button" onclick="js2oc2('Gavin','18')">js调用oc的按钮2</button>
<!--    用于显示oc点击事情的成果    -->
<h1 id=labelId>label</h1>
// OC的按钮
_button1 = [[UIButton alloc] initWithFrame:CGRectMake(100, self.view.bounds.size.height/2 + 100, 200,40)];
[_button1 setTitle:@"oc2js无参" forState:UIControlStateNormal];
_button1.backgroundColor = [UIColor grayColor];
[_button1 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[_button1 addTarget:self action:@selector(button1Click:)forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_button1];
_button2 = [[UIButton alloc]initWithFrame:CGRectMake(100,self.view.bounds.size.height/2 + 150, 200,40)];
[_button2 setTitle:@"oc2js有参"forState:UIControlStateNormal];
_button2.backgroundColor = [UIColor grayColor];
[_button2 setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
[_button2 addTarget:self action:@selector(button2Click:)forControlEvents:UIControlEventTouchUpInside];
[self.view addSubview:_button2];

1. JS调用OC办法

JS按钮绑定的函数内给OC发送音讯window.webkit.messageHandlers.这个方位是音讯称号.postMessage();,音讯称号在oc里注册js音讯的时分用到。详细如下:

// JS给OC发送音讯
function js2oc1() {
    window.webkit.messageHandlers.noParamsFunction.postMessage('我是js办法传过来的数据');
}
function js2oc2(x,y) {
    window.webkit.messageHandlers.haveParamsFunction.postMessage({name:x,age:y});
}

WKWebView 需要恪守WKScriptMessageHandler协议,并注册JS音讯:

WKUserContentController *_userContentController = [[WKUserContentController alloc] init];
// 恪守WKScriptMessageHandler协议。注册JS音讯,name必须JS发送音讯时的名字对应
[_userContentController addScriptMessageHandler:self name:@"noParamsFunction"];
[_userContentController addScriptMessageHandler:self name:@"haveParamsFunction"];
WKWebViewConfiguration *_configuration = [[WKWebViewConfiguration alloc] init];
_configuration.userContentController = _userContentController;
_wkWeb = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width,self.view.bounds.size.height/2 - 20) configuration:_configuration];

WKScriptMessageHandler协议只有一个办法:

@protocol WKScriptMessageHandler <NSObject>
@required
/*! @abstract Invoked when a script message is received from a webpage.
 @param userContentController The user content controller invoking the
 delegate method.
 @param message The script message received.
 */
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message;
@end

实现该办法。办法功能就是承受JS音讯。

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    // WKScriptMessage 类的name属性是音讯称号,body是发送的数据
    NSLog(@"message.name:%@", message.name);
    NSLog(@"message.body:%@", message.body);
}

写了这么多咱们运行一遍看效果:

WKWebview与JavaScript 交互(一)交互本地html

2. OC调用JS函数

WKWebView 有个办法- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^ _Nullable)(_Nullable id, NSError * _Nullable error))completionHandler;能够实现执行JS代码,原理比较像html页面注入代码。这办法调用一般在页面加载完结后。假如不是写在按钮点击事情内,你能够选在在WKWebView的WKNavigationDelegate协议署理办法- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation;内调用。

贴上刚加载完的页面做比照。白色背景的上半页面是html区域,灰色背景的下半页面是OC控件。下面的OC按钮被点击后html区域的label字样会改变。

WKWebview与JavaScript 交互(一)交互本地html

按钮点击事情内调用:

- (void)button1Click:(UIButton *)button {
    // OC给JS发送音讯
    [_wkWeb evaluateJavaScript:@"oc2js1()" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSLog(@"error %@", error);
    }];
}

WKWebview与JavaScript 交互(一)交互本地html

- (void)button2Click:(UIButton *)button {
    // OC给JS发送音讯
    [_wkWeb evaluateJavaScript:@"oc2js2('你','好')" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSLog(@"error %@", error);
    }];
}

WKWebview与JavaScript 交互(一)交互本地html

demo工程能够到我的Github下载。

总结

咱们的目的想监听长途网页按钮点击事情到这里仍是不能实现。别人不会在自己的网页JS代码中给你添加window.webkit.messageHandlers.(messagename).postMessage让你调用。所以鄙人一章中继续。

WKWebview与JavaScript 交互(二)监听长途网页点击事情