1、初始化wkwebview
- (WKWebView *)wkWebView{
if (!_wkWebView) {
//设置网页的配置文件
WKWebViewConfiguration * Configuration = [[WKWebViewConfiguration alloc]init];
//允许视频播放
Configuration.allowsAirPlayForMediaPlayback = YES;
// 允许在线播放
Configuration.allowsInlineMediaPlayback = YES;
// 允许可以与网页交互,选择视图
Configuration.selectionGranularity = YES;
// web内容处理池
Configuration.processPool = [[WKProcessPool alloc] init];
//自定义配置,一般用于 js调用oc方法(OC拦截URL中的数据做自定义操作)
WKUserContentController * UserContentController = [[WKUserContentController alloc]init];
// 添加消息处理,注意:self指代的对象需要遵守WKScriptMessageHandler协议,结束时需要移除
[UserContentController addScriptMessageHandler:self name:@"WXPay"];
// 是否支持记忆读取
Configuration.suppressesIncrementalRendering = YES;
// 允许用户更改网页的设置
Configuration.userContentController = UserContentController;
_wkWebView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, KScreenWidth, 200) configuration:Configuration];
_wkWebView.backgroundColor = [UIColor colorWithRed:240.0/255 green:240.0/255 blue:240.0/255 alpha:1.0];
// 设置代理
_wkWebView.navigationDelegate = self;
_wkWebView.UIDelegate = self;
//kvo 添加进度监控
// [_wkWebView addObserver:self forKeyPath:NSStringFromSelector(@selector(estimatedProgress)) options:0 context:WkwebBrowserContext];
//开启手势触摸_wkWebView.allowsBackForwardNavigationGestures = YES;
}
return _wkWebView;
}
2、获取js返回的信息
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
}
3、原生调用js方法
[self.webView evaluateJavaScript:@"function('action')" completionHandler:nil];
4、拦截url(可在此方法中实现判断url执行相应的oc方法):js会尝试加载某个URL,客户端在加载前拦截这个URL,通过解析这个URL识别它的内容,调用相应的原生方法,并阻止浏览器加载这个URL
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler{
NSLog(@"%@",navigationAction.request.URL.absoluteString);
NSURL *url = navigationAction.request.URL;
NSString *urlStr = url.absoluteString;
if ([urlStr isEqualToString:@"xxx"]) {
// do something ;
//不允许跳转
decisionHandler(WKNavigationActionPolicyCancel);
return;
}
//允许跳转decisionHandler(WKNavigationActionPolicyAllow);
}
网友评论