iOS WKWebView使用 JS交互

iOS8以后,苹果推出了新框架Webkit,提供了替换UIWebView的组件WKWebView。摆脱过去 UIWebView的老、旧、笨重,特别是内存占用量巨大的问题,它使用Nitro JavaScript引擎,这意味着所有第三方浏览器运行JavaScript将会跟safari一样快。

WKWebView的特点:

  • 支持HTML5 新特性
  • 高达60fps滚动刷新频率与内置手势
  • 与Safari相容的JavaScript引擎
  • 在性能、稳定性方面有很大提升,占用内存更少
  • 可获取加载进度等(设置进度条)

WKWebView 使用

1.导入头文件
import
2.初始化
- (instancetype)initWithFrame:(CGRect)frame
                configuration:(WKWebViewConfiguration*)configuration

(⚠️ ⚠️ WKWebViewConfiguration 是一个属性的集合 用来初始化web视图。)

//初始化一个WKWebViewConfiguration对象
WKWebViewConfiguration *config = [WKWebViewConfiguration new];
//初始化偏好设置属性:preferences
config.preferences = [WKPreferences new];
//The minimum font size in points default is 0;
config.preferences.minimumFontSize = 10;
//是否支持JavaScript
config.preferences.javaScriptEnabled = YES;
//不通过用户交互,是否可以打开窗口
config.preferences.javaScriptCanOpenWindowsAutomatically = NO;

WKWebView *webView = [[WKWebView alloc]initWithFrame:self.view.frame configuration:config];
[self.view addSubview:webView];
3.delegate代理
// WKNavigationDelegate主要处理页面跳转相关事件
self.webView.navigationDelegate = self;
// WKUIDelegate主要处理一些页面上的事件,如警告框、对话框等。
self.webView.UIDelegate = self;

实现代理方法:
WKNavigationDelegate

// 判断是否允许跳转
- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler;

// 在响应完成时,调用的方法。如果设置为不允许响应,web内容就不会传过来
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler;

// 开始加载时调用
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(null_unspecified WKNavigation *)navigation;

// 接收到服务器跳转请求之后调用
- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(null_unspecified WKNavigation *)navigation;

// 加载错误时调用
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;

// 当内容开始返回时调用
- (void)webView:(WKWebView *)webView didCommitNavigation:(null_unspecified WKNavigation *)navigation;

// 加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(null_unspecified WKNavigation *)navigation;

// 页面加载失败时调用
- (void)webView:(WKWebView *)webView didFailNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error;

// 当webView需要响应身份验证时调用(如需验证服务器证书)
- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler;

// 当webView的web内容进程被终止时调用。(iOS 9.0之后)
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView API_AVAILABLE(macosx(10.11), ios(9.0));

WKUIDelegate

// 警告框
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler;

// 确认框
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler;

// 确认框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler;
4.加载url
NSURL *url = [NSURL URLWithString:self.urlStr];
[self.webView loadRequest:[NSURLRequest requestWithURL:url]];
[self.view addSubview:self.webView];
5.WKWebView属性的监听
// 添加KVO监听
// 否正在加载
[self.webView addObserver:self
               forKeyPath:@"loading"
                  options:NSKeyValueObservingOptionNew
                  context:nil];
// 获取页面标题
[self.webView addObserver:self
               forKeyPath:@"title"
                  options:NSKeyValueObservingOptionNew
                  context:nil];
// 当前页面载入进度
[self.webView addObserver:self
               forKeyPath:@"estimatedProgress"
                  options:NSKeyValueObservingOptionNew
                  context:nil];

注意 ⚠️ 注意 ⚠️ 注意 ⚠️ 重要的事情说三遍

[_webView removeObserver:self forKeyPath:@"loading" context:nil];
[_webView removeObserver:self forKeyPath:@"title" context:nil];
[_webView removeObserver:self forKeyPath:@"estimatedProgress" context:nil];

监听方法

#pragma mark - KVO监听函数
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{
  if ([keyPath isEqualToString:@"title"]) {
      self.title = self.webView.title;
  }else if([keyPath isEqualToString:@"loading"]){
      NSLog(@"loading");
  }
  else if ([keyPath isEqualToString:@"estimatedProgress"]){
      // estimatedProgress取值范围是0-1;
      self.progressView.progress = self.webView.estimatedProgress;
  }

  if (!self.webView.loading) {
      [UIView animateWithDuration:0.5 animations:^{
          self.progressView.alpha = 0;
      }];
  }    
}
6.JS交互

可以直接添加对约定的ScriptMessage的监听,即可实现JS调用OC。所有的操作都是通过WKUserContentController来处理的

WKUserContentController *conntentController = self.webView.configuration.userContentController;

首先在JS代码中加入对事先约定好的 ScriptMessage(JS事件)的调用

window.webkit.messageHandlers.<事件名>.postMessage(需要传递的数据)
JS.png

OC端添加一个名为 @”getAudio” 的 JS的监听

[conntentController addScriptMessageHandler:self name:@"getAudio"];

移除监听

[conntentController removeScriptMessageHandlerForName:@"closeWindow"];

处理监听到的事件

// 当接收到一个ScriptMessage(JS事件)时调用
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message;

OC调用JS

- (void)evaluateJavaScript:(NSString *)javaScriptString completionHandler:(void (^ _Nullable)(_Nullable id, NSError * _Nullable error))completionHandler;
OC.png

欢迎补充 !!

你可能感兴趣的:(iOS WKWebView使用 JS交互)