JS與OC交互、js事件注入、修改js方法實(shí)現(xiàn)

序言

由于UIWebview即將廢棄,相比較于WKWebview,通過測(cè)試即可發(fā)現(xiàn)UIWebview占用更多內(nèi)存,且內(nèi)存很夸張。WKWebView網(wǎng)頁加載速度也有提升,但是并不像內(nèi)存那樣提升那么多。下面列舉一些其它的優(yōu)勢(shì):

  • 更多的支持HTML5的特性
  • 官方宣稱的高達(dá)60fps的滾動(dòng)刷新率以及內(nèi)置手勢(shì)
  • Safari相同的JavaScript引擎
  • 將UIWebViewDelegate與UIWebView拆分成了14類與3個(gè)協(xié)議(官方文檔說明)
  • 另外用的比較多的,增加加載進(jìn)度屬性:estimatedProgress
    本文主要以WKWebview交互為主介紹。分為三部分:1、JS與OC交互 2、js事件注入 3、修改js系統(tǒng)或者自定義方法實(shí)現(xiàn)

一、JS與OC交互

  • MessageHandle交互通過

  • 1.1 創(chuàng)建WKWebViewConfiguration對(duì)象,配置各個(gè)API對(duì)應(yīng)的MessageHandler。
#pragma mark --  初始化
- (void)initView{
       WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
       WKPreferences *preference = [WKPreferences new];
       preference.javaScriptCanOpenWindowsAutomatically = YES;
       preference.minimumFontSize = 40.0;
       configuration.preferences = preference;
       
       // WKWebView
       CGRect webViewFrame = CGRectMake(0, 180, self.view.bounds.size.width, self.view.bounds.size.height * 0.8);
       self.webView = [[WKWebView alloc] initWithFrame:webViewFrame configuration:configuration];
       NSString *urlStr = [[NSBundle mainBundle] pathForResource:@"index.html" ofType:nil];
       NSURL *fileURL = [NSURL fileURLWithPath:urlStr];
       [self.webView loadFileURL:fileURL allowingReadAccessToURL:fileURL];
       
       self.webView.navigationDelegate = self;
       self.webView.UIDelegate = self;
       [self.view addSubview:self.webView];
       [self addJSActionByOC];
}
  • 配置MessageHandler
    需要注意的是addScriptMessageHandler很容易引起循環(huán)引用,導(dǎo)致控制器無法被釋放,所以需要移除MessageHandler
#pragma mark --  生命周期
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    // addScriptMessageHandler 很容易導(dǎo)致循環(huán)引用
    // 控制器 強(qiáng)引用了WKWebView,WKWebView copy(強(qiáng)引用了)configuration, configuration copy (強(qiáng)引用了)userContentController
    // userContentController 強(qiáng)引用了 self (控制器)
    // js調(diào)用oc方之前要進(jìn)行注冊(cè)
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Location"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Share"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"Color"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"GoBack"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"ocZRAction"];
    [self.webView.configuration.userContentController addScriptMessageHandler:self name:@"asyncAction"];
}
- (void)viewWillDisappear:(BOOL)animated {
    [super viewWillDisappear:animated];
    
    // 因此這里要記得移除handlers
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Location"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Share"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"Color"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"GoBack"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"ocZRAction"];
    [self.webView.configuration.userContentController removeScriptMessageHandlerForName:@"asyncAction"];
}
  • 1.2 實(shí)現(xiàn)協(xié)議方法
    這實(shí)現(xiàn)三個(gè)協(xié)議<WKNavigationDelegate,WKUIDelegate, WKScriptMessageHandler>
    WKUIDelegate是因?yàn)槲以贘S中彈出了alert 。
  • js代碼
        <input type="button" value="oc攔截alert提示" onclick="colorClick()" />
        function colorClick() {
                alert('55555')
            }
  • oc代碼,js alert(),會(huì)觸發(fā)WKUIDelegate代理中的webView:runJavaScriptAlertPanelWithMessage:方法執(zhí)行
#pragma mark - WKUIDelegate
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:message preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    
    [self presentViewController:alert animated:YES completion:nil];
}

WKScriptMessageHandler是因?yàn)槲覀円幚鞪S調(diào)用OC方法的請(qǐng)求。
WKScriptMessage有兩個(gè)關(guān)鍵屬性name 和 body。
因?yàn)槲覀兘o每一個(gè)OC 方法取了一個(gè)name,那么我們就可以根據(jù)name 來區(qū)分執(zhí)行不同的方法。body 中存著JS 要給OC 傳的參數(shù)。

  • js代碼
        <input type="button" value="調(diào)用oc方法傳遞事件" onclick="goBack()" />
        function goBack() {
                window.webkit.messageHandlers.asyncAction.postMessage("傳遞數(shù)據(jù)");
            }
  • oc代碼
#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    // message.body  --  Allowed types are NSNumber, NSString, NSDate, NSArray,NSDictionary, and NSNull.
    if ([message.name isEqualToString:@"Location"]) {

    } else if ([message.name isEqualToString:@"Share"]) {

    } else if ([message.name isEqualToString:@"Color"]) {

    }else if ([message.name isEqualToString:@"GoBack"]) {
        
    }else if ([message.name isEqualToString:@"asyncAction"]) {
        NSLog(@"假死頁面回調(diào)事件");
    }else if ([message.name isEqualToString:@"ocZRAction"]){
        NSLog(@"oc注入方法,調(diào)用oc事件  message = %@",message.body);
        UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"提醒" message:@"調(diào)用成功" preferredStyle:UIAlertControllerStyleAlert];
           [alert addAction:[UIAlertAction actionWithTitle:@"知道了" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {

           }]];
           
           [self presentViewController:alert animated:YES completion:nil];
    }
    
}

二、JS事件注入

  • js代碼

ocAddAction方法在js文件中并沒有定義

        <input type="button" value="oc注入js事件,調(diào)用oc" onclick="ocAddAction()" />
  • OC注入代碼

實(shí)現(xiàn)WKNavigationDelegate協(xié)議方法,執(zhí)行之后會(huì)在WKScriptMessageHandler代理方法中攔截到ocZRAction

#pragma mark - WKNavigationDelegate
///加載完成網(wǎng)頁的時(shí)候才開始注入JS代碼,要不然還沒加載完時(shí)就可以點(diǎn)擊了,就不能調(diào)用我們的代碼了!
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
    NSString *jsCode = @"function ocAddAction(a,b,c){\
        window.webkit.messageHandlers.ocZRAction.postMessage('js注入')\
    }";
    [self.webView evaluateJavaScript:jsCode completionHandler:^(id _Nullable obj, NSError * _Nullable error) {

    }];
}

三、動(dòng)態(tài)修改JS系統(tǒng)函數(shù)或者自定義函數(shù)實(shí)現(xiàn)

  • oc代碼

動(dòng)態(tài)修改alert系統(tǒng)函數(shù)的實(shí)現(xiàn),當(dāng)js中調(diào)用alert函數(shù)時(shí),觸發(fā)的是我們自定義方法

#pragma mark --  通過js注入,修改js內(nèi)部函數(shù)或者系統(tǒng)函數(shù)內(nèi)部實(shí)現(xiàn)
- (void)addJSActionByOC{
    NSString *jsCode = @"alert = (function (oriAlertFunc){ \
                          return function(task)\
                          {\
                           window.webkit.messageHandlers.ocZRAction.postMessage(task);\
                           oriAlertFunc.call(alert,task);\
                          }\
                          })(alert);";
         
    //injected the method when H5 starts to create the DOM tree
    [self.webView.configuration.userContentController addUserScript:[[WKUserScript alloc] initWithSource:jsCode injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:YES]];
}
  • js代碼
        <input type="button" value="獲取定位" onclick="locationClick()" />
       function locationClick() {
                alert('4444')
            }

URL Scheme攔截的問題,這里不做贅述,請(qǐng)看demo
JS注入詳情
參考鏈接:
鏈接一
鏈接二

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容