//
//  ViewController.m
//  ChinaDailyForiPad
//
//  Created by 黄江涛 on 2018/4/4.
//  Copyright © 2018年 https://www.jianshu.com/u/e15d1f644bea All rights reserved.
//

#import "WKSuperViewController.h"
#import <WebKit/WebKit.h>
#import "PrefixHeader.pch"
//导航栏


//#import "md5.h"
#import "WeakWebViewScriptMessageDelegate.h"



@interface WKSuperViewController ()<WKScriptMessageHandler, WKUIDelegate, WKNavigationDelegate>
    
    @property (nonatomic, strong) WKWebView *  webView;
    @property (nonatomic, strong) UIProgressView * progressView;
    
    @end

@implementation WKSuperViewController
- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:YES];
    [MobClick beginLogPageView:self.titleStr];
    
}

- (void)viewDidDisappear:(BOOL)animated {
    [super viewDidDisappear:YES];
        [MobClick endLogPageView:self.titleStr];
    

}


- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    if ([self.pathStr isEqualToString:@"https://wallet.95516.com/s/wl/webV3/activity/vInvite/html/snsIndex.html?code=bdyx&from=groupmessage&isappinstalled=0"]) {
        self.navigationController.navigationBar.barTintColor = [UIColor colorWithHex:0xbe0124];
        
        [self.transitionCoordinator animateAlongsideTransition:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
            self.navigationController.navigationBar.barTintColor = [UIColor colorWithHex:0xbe0124];
            [self.navigationController.navigationBar setBackgroundImage:[UIImage  imageNamed:@""] forBarMetrics:UIBarMetricsDefault];
        } completion:^(id<UIViewControllerTransitionCoordinatorContext>  _Nonnull context) {
        }];
        
    }
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setupNavigationItem];
    [self.view addSubview:self.webView];
    [self.view addSubview:self.progressView];
    [self.webView addObserver:self
                   forKeyPath:NSStringFromSelector(@selector(estimatedProgress))
                      options:0
                      context:nil];
  
        [self.webView addObserver:self
                       forKeyPath:@"title"
                          options:NSKeyValueObservingOptionNew
                          context:nil];
    
    self.view.backgroundColor =[UIColor whiteColor];
    
}
-(void)observeValueForKeyPath:(NSString *)keyPath
                     ofObject:(id)object
                       change:(NSDictionary<NSKeyValueChangeKey,id> *)change
                      context:(void *)context{
    
    if ([keyPath isEqualToString:NSStringFromSelector(@selector(estimatedProgress))]
        && object == _webView) {
        
        NSLog(@"网页加载进度 = %f",_webView.estimatedProgress);
        self.progressView.progress = _webView.estimatedProgress;
        if (_webView.estimatedProgress >= 1.0f) {
            dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.3 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
                self.progressView.progress = 0;
            });
        }
        
    }else if([keyPath isEqualToString:@"title"]
             && object == _webView){
        self.navigationItem.title = self.titleStr;
    }else{
        [super observeValueForKeyPath:keyPath
                             ofObject:object
                               change:change
                              context:context];
    }
}
    
    
- (void)setupNavigationItem{
    // 后退按钮
//    UIButton * goBackButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [goBackButton setImage:[UIImage imageNamed:@"backbutton"] forState:UIControlStateNormal];
//    [goBackButton addTarget:self action:@selector(goBackAction:) forControlEvents:UIControlEventTouchUpInside];
//    goBackButton.frame = CGRectMake(0, 0, 30, StatusBarAndNavigationBarHeight);
//    UIBarButtonItem * goBackButtonItem = [[UIBarButtonItem alloc] initWithCustomView:goBackButton];
//    
//    UIBarButtonItem * jstoOc = [[UIBarButtonItem alloc] initWithTitle:@"首页" style:UIBarButtonItemStyleDone target:self action:@selector(localHtmlClicked)];
//    self.navigationItem.leftBarButtonItems = @[goBackButtonItem,jstoOc];
    
    UIButton * button_2 = [UIButton buttonWithType:UIButtonTypeCustom];
    button_2.frame = CGRectMake(-30, 0, 20, 40);
    button_2.titleLabel.textAlignment =NSTextAlignmentLeft;
    //    [button_2 setTitle:@"asdasd按时打发第三方" forState:UIControlStateNormal];
    [button_2 setImage:[UIImage imageNamed:@"返回"] forState:UIControlStateNormal];
    //    [button_2 setBackgroundColor:[UIColor redColor]];
    //    [button_2 setTitleColor:[UIColor colorWithRed:12.0 green:12.0 blue:12.0 alpha:1] forState:UIControlStateNormal];
    [button_2 addTarget:self action:@selector(buttonClick_1) forControlEvents:UIControlEventTouchUpInside];
    UIBarButtonItem * backButtonItem_2 = [[UIBarButtonItem alloc] initWithCustomView:button_2];
    
    self.navigationItem.leftBarButtonItem = backButtonItem_2;
    
   
//    // 刷新按钮
//    UIButton * refreshButton = [UIButton buttonWithType:UIButtonTypeCustom];
//    [refreshButton setImage:[UIImage imageNamed:@"webRefreshButton"] forState:UIControlStateNormal];
//    [refreshButton addTarget:self action:@selector(refreshAction:) forControlEvents:UIControlEventTouchUpInside];
//    refreshButton.frame = CGRectMake(0, 0, 30, StatusBarAndNavigationBarHeight);
//    UIBarButtonItem * refreshButtonItem = [[UIBarButtonItem alloc] initWithCustomView:refreshButton];
//
//    UIBarButtonItem * ocToJs = [[UIBarButtonItem alloc] initWithTitle:@"OC调用JS" style:UIBarButtonItemStyleDone target:self action:@selector(ocToJs)];
//    self.navigationItem.rightBarButtonItems = @[refreshButtonItem, ocToJs];
    
}
-(void)buttonClick_1{
    if (self.webView.canGoBack==YES) {
        [self.webView goBack];
    }else{
        [self.navigationController popViewControllerAnimated:YES];
    }

    
}
#pragma mark -- Event Handle
    
- (void)goBackAction:(id)sender{
    [_webView goBack];
}
    
- (void)localHtmlClicked{
    NSString *path = [[NSBundle mainBundle] pathForResource:@"JStoOC.html" ofType:nil];
    NSString *htmlString = [[NSString alloc]initWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
    [_webView loadHTMLString:htmlString baseURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] bundlePath]]];
}
    
- (void)refreshAction:(id)sender{
    [_webView reload];
}
    
- (void)ocToJs{
    /**
     *第一个值
     */
     //kkanface  是写死的 常量
    /**
     *第二个值
     */
       //sunkidsun   是银行这边要传的值  (用户昵称)
    /**
     *第三个值
     */
    //18501667794是银行这边要传的值  (手机号码)
    /**
     *第四个值
     */
   //4   是写死的 常量
    /**
     *第五个值
     */
    //de324a49d54799f0cf499ef66238f7a0 这个是拼接好的值
    //拼接方法
    // 遍历排序后的字典，将所有参数按"key=value&key=value"格式拼接在一起最后拼接上&KkweInfo23255625
    //eg:accountName=sunkidshu&authName=kkanface&loginType=4&telphone=17775005839&KkweInfo23255625
    //做MD5加密
    //[md5 md55:@"accountName=sunkidshu&authName=kkanface&loginType=4&telphone=17775005839&KkweInfo23255625"];
    /**
     *将这五个值拼接成字符串以逗号隔开
     eg:@"kkanface,sunkidshu,18501667794,4,de324a49d54799f0cf499ef66238f7a0";
     */
    NSString *demoString = @"kkanface,sunkidshu,18501667794,4,de324a49d54799f0cf499ef66238f7a0";
//用oc代码调用js 的方法
    NSString *jsString = [NSString stringWithFormat:@"showInfoFromJava('%@')",demoString];
    [_webView evaluateJavaScript:jsString completionHandler:^(id _Nullable data, NSError * _Nullable error) {
        
//返回值
        NSLog(@"%@",data);
          NSLog(@"%@",error);
    }];
    [_webView evaluateJavaScript:@"" completionHandler:nil];
    
}
    
#pragma mark -- getters and setters
    
- (UIProgressView *)progressView
    {
      
        if (!_progressView){
            _progressView = [[UIProgressView alloc] initWithFrame:CGRectMake(0, Height_TopBar + 1, self.view.frame.size.width, 2)];
            _progressView.tintColor = [UIColor greenColor];
            _progressView.trackTintColor = [UIColor clearColor];
        }
        return _progressView;
    }
    
- (WKWebView *)webView{
    
    if(_webView == nil){
        

        //创建网页配置对象
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        
        //创建设置对象
        WKPreferences *preference = [[WKPreferences alloc]init];

        //最小字体大小 当将javaScriptEnabled属性设置为NO时，可以看到明显的效果
        preference.minimumFontSize = 0;

        //设置是否支持javaScript 默认是支持的
        preference.javaScriptEnabled = YES;

        // 在iOS上默认为NO，表示是否允许不经过用户交互由javaScript自动打开窗口
        preference.javaScriptCanOpenWindowsAutomatically = YES;
        config.preferences = preference;
        

        // 是使用h5的视频播放器在线播放, 还是使用原生播放器全屏播放
        config.allowsInlineMediaPlayback = YES;

    
        //设置视频是否需要用户手动播放  设置为NO则会允许自动播放
        if ([[[UIDevice currentDevice] systemVersion] floatValue] >= 10.0) {
           config.mediaTypesRequiringUserActionForPlayback = YES;
        } else if([[[UIDevice currentDevice] systemVersion] floatValue] >= 9.0 && [[[UIDevice currentDevice] systemVersion] floatValue] < 10.0 ) {
            config.requiresUserActionForMediaPlayback = YES;
        }else{
            config.mediaPlaybackRequiresUserAction = YES;
        }
        
        
        
       
        
    
        //设置是否允许画中画技术 在特定设备上有效
        if (@available(iOS 9.0,*)) {
            config.allowsPictureInPictureMediaPlayback = YES;
        }
        

        //设置请求的User-Agent信息中应用程序名称 iOS9后可用
        config.applicationNameForUserAgent = @"ChinaDailyForiPad";
        

        //自定义的WKScriptMessageHandler 是为了解决内存不释放的问题
        WeakWebViewScriptMessageDelegate *weakScriptMessageDelegate = [[WeakWebViewScriptMessageDelegate alloc] initWithDelegate:self];

        //这个类主要用来做native与JavaScript的交互管理
        WKUserContentController * wkUController = [[WKUserContentController alloc] init];

        //注册一个name为jsToOcNoPrams的js方法
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"jsToOcNoPrams"];
        [wkUController addScriptMessageHandler:weakScriptMessageDelegate  name:@"jsToOcWithPrams"];
        config.userContentController = wkUController;
     
        NSString *jSString = nil;
        if ([self.titleStr isEqualToString:@"短视频"]) {
            jSString = @"var meta = document.createElement('meta'); meta.setAttribute('name', 'viewport'); meta.setAttribute('content', 'width=device-width'); document.getElementsByTagName('head')[0].appendChild(meta);javascript:function setTop(){document.querySelector('.turnoff').style.position='inherit';}setTop();javascript:function setTop1()javascript:function setTop5(){document.querySelector('.site-header-bg').style.display='none';}setTop5();";
        }else if([self.titleStr isEqualToString:@"社保计算器"]){
            
            
//            jSString=@"javascript:function setTop6(){}setTop6();javascript:function setTop7(){document.querySelector('.nb-invite-wrap-base').style.width='0px';}setTop7();";
           jSString = @"javascript:function setTop11(){document.querySelector('.top_denglu').style.display='none';document.querySelector('.col-sm-6').style.display='none';document.querySelector('.navbar').style.display='none';document.querySelector('#newBridge').style.opacity='0';document.querySelector('.row').style.display='none';document.querySelector('.footer1').style.display='none';}setTop11();";
        }
   
        jSString=@"javascript:function setTop3(){document.querySelector('.head').style.display=\"none\";}setTop3();";
        
        WKUserScript *wkUScript = [[WKUserScript alloc] initWithSource:jSString injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
        [config.userContentController addUserScript:wkUScript];
        if(IS_IPhoneX_All){
        _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, SCREEN_WIDTHL, SCREEN_HEIGHTL-cl_kNavigationBarHeight-20) configuration:config];
        }else{
       _webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, cl_kNavigationBarHeight, SCREEN_WIDTHL, SCREEN_HEIGHTL - cl_kNavigationBarHeight) configuration:config];
        }


        _webView.UIDelegate = self;

        _webView.navigationDelegate = self;

        _webView.allowsBackForwardNavigationGestures = YES;

//       WKBackForwardList * backForwardList = [_webView backForwardList];
        
  
        //访问地址
        NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:self.pathStr]];
                [request addValue:nil forHTTPHeaderField:@"Cookie"];
                [_webView loadRequest:request];
        
    }
    return _webView;
}

- (NSString *)readCurrentCookieWithDomain:(NSString *)domainStr{
    NSHTTPCookieStorage*cookieJar = [NSHTTPCookieStorage sharedHTTPCookieStorage];
    NSMutableString * cookieString = [[NSMutableString alloc]init];
    for (NSHTTPCookie*cookie in [cookieJar cookies]) {
        NSLog(@"%@",cookie.name);
        NSLog(@"%@",cookie.value);
        [cookieString appendFormat:@"%@=%@;",cookie.name,cookie.value];
    }

    if ([cookieString hasSuffix:@";"]) {
        [cookieString deleteCharactersInRange:NSMakeRange(cookieString.length - 1, 1)];
    }
    
    return cookieString;
}

- (void)getCookie{

    NSHTTPCookieStorage *cookieStorage = [NSHTTPCookieStorage sharedHTTPCookieStorage];

    NSString *JSFuncString =
    @"function setCookie(name,value,expires)\
    {\
    var oDate=new Date();\
    oDate.setDate(oDate.getDate()+expires);\
    document.cookie=name+'='+value+';expires='+oDate+';path=/'\
    }\
    function getCookie(name)\
    {\
    var arr = document.cookie.match(new RegExp('(^| )'+name+'=([^;]*)(;|$)'));\
    if(arr != null) return unescape(arr[2]); return null;\
    }\
    function delCookie(name)\
    {\
    var exp = new Date();\
    exp.setTime(exp.getTime() - 1);\
    var cval=getCookie(name);\
    if(cval!=null) document.cookie= name + '='+cval+';expires='+exp.toGMTString();\
    }";

    NSMutableString *JSCookieString = JSFuncString.mutableCopy;
    for (NSHTTPCookie *cookie in cookieStorage.cookies) {
        NSString *excuteJSString = [NSString stringWithFormat:@"setCookie('%@', '%@', 1);", cookie.name, cookie.value];
        [JSCookieString appendString:excuteJSString];
    }

    [_webView evaluateJavaScript:JSCookieString completionHandler:nil];
    
}

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    NSLog(@"name:%@\\\\n body:%@\\\\n frameInfo:%@\\\\n",message.name,message.body,message.frameInfo);
    NSDictionary * parameter = message.body;
    if([message.name isEqualToString:@"jsToOcNoPrams"]){
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"js调用到了oc" message:@"不带参数" preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }])];
        [self presentViewController:alertController animated:YES completion:nil];
        
    }else if([message.name isEqualToString:@"jsToOcWithPrams"]){
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"js调用到了oc" message:parameter[@"params"] preferredStyle:UIAlertControllerStyleAlert];
        [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        }])];
        [self presentViewController:alertController animated:YES completion:nil];
    }
    
}
    
#pragma mark -- WKNavigationDelegate

- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
}

- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    [self.progressView setProgress:0.0f animated:NO];
}

- (void)webView:(WKWebView *)webView didCommitNavigation:(WKNavigation *)navigation {
    
}

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
    
    [self getCookie];
    
    if ([self.titleStr isEqualToString:@"社保计算器"]) {
        NSString *jsString = @"javascript:function setTop11(){document.querySelector('.top_denglu').style.display='none';document.querySelector('.col-sm-6').style.display='none';document.querySelector('.navbar').style.display='none';document.querySelector('#newBridge').style.opacity='0';document.querySelector('.row').style.display='none';document.querySelector('.footer1').style.display='none';}setTop11();";
        [_webView evaluateJavaScript:jsString completionHandler:^(id _Nullable data, NSError * _Nullable error) {
            

        }];
    }
    
    
  
}

- (void)webView:(WKWebView *)webView didFailNavigation:(WKNavigation *)navigation withError:(NSError *)error {
    [self.progressView setProgress:0.0f animated:NO];
}

- (void)webView:(WKWebView *)webView didReceiveServerRedirectForProvisionalNavigation:(WKNavigation *)navigation {
    
}

- (void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler {
    


   
    
    
    
    
    
    
    
    
    
    NSString * urlStr = navigationAction.request.URL.absoluteString;
    NSLog(@"发送跳转请求：%@",urlStr);

    if([self.titleStr isEqualToString:@"支付宝抢红包"]){
        
        NSURL *url = [NSURL URLWithString:urlStr];
        
        
        if ([urlStr containsString:@"alipays://"]) {
            if ([[UIApplication sharedApplication] canOpenURL:url]) {
                [[UIApplication sharedApplication] openURL:url];
            }
        }
        
        
    }
    
    
    
//    NSString *htmlHeadString = @"github://";
   if([urlStr containsString:@"8qqai"]){
//        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"通过截取URL调用OC" message:@"你想前往我的Github主页?" preferredStyle:UIAlertControllerStyleAlert];
//        [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
//
//        }])];
//        [alertController addAction:([UIAlertAction actionWithTitle:@"打开" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            NSURL * url = [NSURL URLWithString:[urlStr stringByReplacingOccurrencesOfString:@"github://callName_?" withString:@""]];
//            [[UIApplication sharedApplication] openURL:url];
//
//        }])];
//        [self presentViewController:alertController animated:YES completion:nil];
        
        decisionHandler(WKNavigationActionPolicyCancel);
        
    }else{
        decisionHandler(WKNavigationActionPolicyAllow);
    }
    
    
}
- (void)webView:(WKWebView *)webView decidePolicyForNavigationResponse:(WKNavigationResponse *)navigationResponse decisionHandler:(void (^)(WKNavigationResponsePolicy))decisionHandler{
    NSString * urlStr = navigationResponse.response.URL.absoluteString;
    NSLog(@"当前跳转地址：%@",urlStr);
  if ([self.titleStr isEqualToString:@"银联抢红包"]) {
      
      NSURL *url = [NSURL URLWithString:urlStr];
      
      
      if ([urlStr containsString:@"https://itunes.apple.com/cn/app/"]) {
          if ([[UIApplication sharedApplication] canOpenURL:url]) {
              [[UIApplication sharedApplication] openURL:url];
          }
      }
      
  }
    if([self.titleStr isEqualToString:@"支付宝抢红包"]){
        
        NSURL *url = [NSURL URLWithString:urlStr];
        
        
        if ([urlStr containsString:@"alipays://"]) {
            if ([[UIApplication sharedApplication] canOpenURL:url]) {
                [[UIApplication sharedApplication] openURL:url];
            }
        }
        
        
    }
    
    
    decisionHandler(WKNavigationResponsePolicyAllow);

}

- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
    NSURLCredential * newCred = [[NSURLCredential alloc] initWithUser:@"user123" password:@"123" persistence:NSURLCredentialPersistenceNone];
    //[challenge.sender useCredential:newCred forAuthenticationChallenge:challenge];
    completionHandler(NSURLSessionAuthChallengeUseCredential,newCred);
    
    
    
    
}
    
    //进程被终止时调用
- (void)webViewWebContentProcessDidTerminate:(WKWebView *)webView{
    
}
    
#pragma mark -- WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"HTML的弹出框" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    [alertController addAction:([UIAlertAction actionWithTitle:@"OK" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}
- (WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures {
    if (!navigationAction.targetFrame.isMainFrame) {
        [webView loadRequest:navigationAction.request];
    }
    return nil;
}
    
- (void)dealloc{
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"jsToOcNoPrams"];
    [[_webView configuration].userContentController removeScriptMessageHandlerForName:@"jsToOcWithPrams"];
    [_webView removeObserver:self
                  forKeyPath:NSStringFromSelector(@selector(estimatedProgress))];
    [self.webView removeObserver:self forKeyPath:@"title"];
    
    self.webView.navigationDelegate = nil;
    self.webView.UIDelegate = nil;
    self.webView.scrollView.delegate = nil;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];

}

    @end
