1、KVO,可监听标题、加载进度、网络地址
//1 添加KVO
[webView addObserver:self forKeyPath:@"estimatedProgress" options:NSKeyValueObservingOptionNew context:NULL];//进度
[webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:NULL];//标题
[webView addObserver:self forKeyPath:@"URL" options:NSKeyValueObservingOptionNew context:NULL];//网址
//2 实现
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context {
if ([keyPath isEqualToString:@"estimatedProgress"]) {
//加载进度值
//webView.estimatedProgress
}else if ([keyPath isEqualToString:@"title"]) {
//网页title
//webView.title
}else if ([keyPath isEqualToString:@"URL"]) {
//网页地址
NSString *urlString = self.webView.URL.absoluteString;
NSURL *url = [NSURL URLWithString:urlString];
}
}else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
2、原生与h5交互-h5主动调用
//1 注册方法
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
config.userContentController = [[WKUserContentController alloc] init];
[config.userContentController addScriptMessageHandler:self name:@"方法名"];
//2 实现
- (void)userContentController:(nonnull WKUserContentController *)userContentController didReceiveScriptMessage:(nonnull WKScriptMessage *)message{
NSString *messageName = message.name;//方法名
NSString *messageBody = message.body;//参数
NSLog(@"messageName=%@ : messageBody=%@",messageName, messageBody);
if ([messageName isEqualToString:@""]) {
}
}
3、原生与h5交互-原生主动调用
// share方法名 a参数
[webView evaluateJavaScript:@"share(a)" completionHandler:^(id _Nullable, NSError * _Nullable error) {
//调用后的回调
}];
4、设置userAgent
if (([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0)) {
[webView setCustomUserAgent:@"你的userAgent"];
} else {
[webView setValue:@"你的userAgent" forKey:@"applicationNameForUserAgent"];
}
5、拦截跳转
//1 设置代理
webView.navigationDelegate = self;
//2 代理方法
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
NSLog(@"navigationAction = %@, request = %@",navigationAction,navigationAction.request.URL);
if ([navigationAction.request.URL.scheme containsString:@"http"]) {
decisionHandler(WKNavigationActionPolicyCancel);//禁止跳转,执行自己的 *** 作
} else {
decisionHandler(WKNavigationActionPolicyAllow);//允许跳转
}
}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)