二. WKWebView篇
先贴上使用的部分html
代码
<body>
<!-- <input type="button" value="按钮" onclick="javascrtpt:window.location.href='https://www.baidu.com'"> -->
<button id="btn" onclick="btnClick()">百度</button>
<button id="btn" onclick="btnActionNoParams()">WK不带参数</button>
<button id="btn" onclick="btnActionWithParams()">WK带参数</button>
<button id="jscontextbtn" onclick="jscontextmethod('参数1')">JSContext按钮</button>
<script>
function btnClick() {
window.location.href = 'jsCallOC://www.baidu.com'
}
function btnActionNoParams() {
window.webkit.messageHandlers.jscalloc1.postMessage(null)
}
function btnActionWithParams() {
window.webkit.messageHandlers.jscalloc2.postMessage({title:'标题',content:'内容',url:'https://www.baidu.com'})
}
function jsTest() {
//alert('这是一个js方法')
console.log('这是一个js方法');
}
function jsTestWithParams(param1) {
//alert(param1);
console.log(param1);
}
</script>
</body>
引入WKWebView
头文件,添加协议:
#import <WebKit/WebKit.h>
@interface WKViewController ()<WKNavigationDelegate,WKScriptMessageHandler,WKUIDelegate>
WKNavigationDelegate:使用拦截url方式与js交互时用到;
WKScriptMessageHandler:使用MessageHandler方式与js交互时用到;
WKUIDelegate:与js有UI上交互时用到;
具体要添加哪种协议,视情况而定。
1. 拦截url方式
创建WKWebView
实例对象,设置协议
self.myWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, 88, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height-88)];
NSURL *url = [[NSBundle mainBundle]URLForResource:@"test.html" withExtension:nil];
[self.myWebView loadRequest:[NSURLRequest requestWithURL:url]];
self.myWebView.navigationDelegate = self;
[self.view addSubview:self.myWebView];
1.1 js调用OC
在navigationDelegate
协议方法中(与UIWebView协议拦截url相似)
-(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
NSURL *url = navigationAction.request.URL; //jscalloc://www.baidu.com
NSString *scheme = [url scheme]; //jscalloc
// NSString *host = [url host]; //www.baidu.com
// NSString *policy = [url query];
if ([scheme isEqualToString:@"jscalloc"]) {
/*
在这里执行OC代码操作
......
*/
UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:@"js调用oc" message:@"点击js方法,调用此oc方法(这是个OC弹框)" preferredStyle:UIAlertControllerStyleAlert];
[alertVC addAction:[UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleCancel handler:nil]];
[self presentViewController:alertVC animated:YES completion:nil];
decisionHandler(WKNavigationActionPolicyCancel);
return;
}
decisionHandler(WKNavigationActionPolicyAllow);
}
注意:
1.如果实现了这个代理方法,就必须得调用decisionHandler这个 block,否则会导致 app 奔溃。block 参数是一个枚举值,WKNavigationActionPolicyCancel代表取消加载,相当于UIWebView的代理方法return NO的情况;
WKNavigationActionPolicyAllow代表允许加载,相当于UIWebView的代理方法中 return YES的情况。
1.2 oc调用js
jsTestWithParams
为js中方法,带一个参数
function jsTestWithParams(param1) {
console.log(param1)
}
在OC中如此调用
-(void)ocCallJS:(UIButton *)btn{
NSString *string = [NSString stringWithFormat:@"jsTestWithParams('%@')",@"这是个js方法哈哈哈"];
//NSString *string = [NSString stringWithFormat:@"jsTest()"];
[self.myWebView evaluateJavaScript:string completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"result:%@\nerror:%@",result,error);
}];
}
可以在浏览器控制台看到此方法打印结果:
2. 使用messageHandlers
,利用WKWebView
的新特性MessageHandler
来实现JS调用原生方法
2.1 js调用oc
这里有两个类:
WKWebViewConfiguration
:WKWebView
配置信息
WKUserContentController
:提供js与oc交互方法
通过addScriptMessageHandler
方法注册js调用oc方法,因为addScriptMessageHandler
会有循坏引用的问题,造成内存泄漏,所以在页面消失时,需移除。
-(void)viewWillAppear:(BOOL)animated{
[super viewWillAppear:animated];
[self.myWebView.configuration.userContentController addScriptMessageHandler:self name:@"jscalloc1"];
[self.myWebView.configuration.userContentController addScriptMessageHandler:self name:@"jscalloc2"];
}
-(void)viewWillDisappear:(BOOL)animated{
[super viewWillDisappear:animated];
[self.myWebView.configuration.userContentController removeScriptMessageHandlerForName:@"jscalloc1"];
[self.myWebView.configuration.userContentController removeScriptMessageHandlerForName:@"jscalloc2"];
}
jscalloc1
和jscalloc2
在上面html代码查看具体的使用
在WKScriptMessageHandler
代理方法中:
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
NSString *str = message.name;
if ([str isEqualToString:@"jscalloc1"]) {
[self jsCallOC];
}else if([str isEqualToString:@"jscalloc2"]){
//获取传过来的参数
//{title:'标题',content:'内容',url:'https://www.baidu.com'}
NSDictionary *dic = message.body;
NSLog(@"dic==%@",dic);
}
}
-(void)jsCallOC{
NSLog(@"js调用oc");
}
2.2 oc调用js
与上述oc调用js是一样的方法
-(void)ocCallJS:(UIButton *)btn{
NSString *string = [NSString stringWithFormat:@"jsTestWithParams('%@')",@"这是个js方法哈哈哈"];
//NSString *string = [NSString stringWithFormat:@"jsTest()"];
[self.myWebView evaluateJavaScript:string completionHandler:^(id _Nullable result, NSError * _Nullable error) {
NSLog(@"result:%@\nerror:%@",result,error);
}];
}