1. 程式人生 > >ios js與oc原生WKWebView方法注入及互動傳值

ios js與oc原生WKWebView方法注入及互動傳值

    上篇文章中,我們整理了關於WKWebView的詳細使用,包含進度條、獲取web title等等內容,這篇文章我們整理下,專案中,我們可能使用到的oc 與 js 原生互動場景下的使用.如有興趣,可加入oneTeam技術交流群: 234713941 ,本人不才小白,多多指教!

     原生載入控制元件使用的是WKWebView.

     1.瀏覽web頁面,點選某個方法,並傳值給oc原生,原生介面做出響應.

     使用場景: 瀏覽web頁面商品,點選檢視詳情,進入原生介面瀏覽商品詳情.

     直接看程式碼:

#import <JavaScriptCore/JavaScriptCore.h>

#import <WebKit/WebKit.h>

@interfaceViewController ()<WKNavigationDelegate,UIScrollViewDelegate,WKUIDelegate,WKScriptMessageHandler>

@property (nonatomicstrongWKWebView *webView;

@end

@implementation ViewController

- (void)viewDidLoad {

    [superviewDidLoad];

self.view .

backgroundColor =[UIColorwhiteColor];

WKWebViewConfiguration *config = [[WKWebViewConfigurationallocinit];

    config.preferences = [[WKPreferencesallocinit];

    config.preferences.minimumFontSize = 10;

    config.preferences.javaScriptEnabled = YES;

    config.preferences.javaScriptCanOpenWindowsAutomatically = 

NO;

    config.userContentController = [[WKUserContentControllerallocinit];

    config.processPool = [[WKProcessPoolallocinit];

self.webView = [[WKWebViewallocinitWithFrame:self.view.bounds

                                      configuration:config];

//記得實現對應協議,不然方法不會實現.

self.webView.UIDelegate = self;

self.webView.navigationDelegate =self;

    [self.viewaddSubview:self.webView];

    [self.webViewloadRequest:[NSURLRequestrequestWithURL:[NSURLURLWithString:@"http://192.168.1.188/index1.html"]]];

// **************** 此處劃重點 **************** //

//添加註入js方法, oc與js端對應實現

    [config.userContentControlleraddScriptMessageHandler:selfname:@"collectSendKey"];

    [config.userContentControlleraddScriptMessageHandler:selfname:@"collectIsLogin"];

//js端程式碼實現例項(此處為js端實現程式碼給大家粘出來示範的!!!):

//window.webkit.messageHandlers.collectSendKey.postMessage({body: 'goodsId=1212'});

}

#pragma mark - WKScriptMessageHandler

//實現js注入方法的協議方法

- (void)userContentController:(WKUserContentController *)userContentController

      didReceiveScriptMessage:(WKScriptMessage *)message {

//找到對應js端的方法名,獲取messge.body

    if ([message.name isEqualToString:@"collectSendKey"]) {

        NSLog(@"%@", message.body);

    }

}

     2.瀏覽web頁面,傳遞值給js介面,js介面通過值判斷處理邏輯.

     使用場景: 瀏覽web頁面商品,加入購物車,js通過oc原生傳遞過去的userId是否為空,來判斷當前app是否登入,未登入,跳轉原生介面登入,已登入,則直接加入購物車

     直接放程式碼:

#pragma mark ---------  WKNavigationDelegate  --------------

// 載入成功,傳遞值給js

- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation

{

    //獲取userId

//傳遞userId給 js端

NSString * userId = DEF_GET_OBJECT(UserID);

   NSString * jsUserId;

    if (!userId) {

        jsUserId =@"";

    }else{

        jsUserId =userId;

    }

    //之所以給userId重新賦值,貌似是如果userId為空null 那麼傳給js端,js說無法判斷,只好說,如果userId為null,重新定義為空字串.如果大家有好的建議,可以在下方留言.   

    //同時,這個地方需要注意的是,js端並不能檢視我們給他傳遞的是什麼值,也無法列印,貌似是語言問題? 還是js騙我文化低,反正,咱們把值傳給他,根據雙方商量好的邏輯,給出判斷,如果正常,那就ok了.

NSString * jsStr  =[NSStringstringWithFormat:@"sendKey('%@')",jsUserId];

    [self.webViewevaluateJavaScript:jsStr completionHandler:^(id_Nullable result, NSError * _Nullable error) {

  //此處可以列印error.

    }];

//js端獲取傳遞值程式碼實現例項(此處為js端實現程式碼給大家粘出來示範的!!!):

//function sendKey(user_id){


           $("#input").val(user_id);
       }

}

//依然是這個協議方法,獲取注入方法名物件,獲取js返回的狀態值.

#pragma mark - WKScriptMessageHandler

- (void)userContentController:(WKUserContentController *)userContentController

      didReceiveScriptMessage:(WKScriptMessage *)message {

//js端判斷如果userId為空,則返回字串@"toLogin"  ,或者返回其它值.  js端程式碼實現例項(此處為js端實現程式碼給大家粘出來示範的!!!):

function collectIsLogin(goods_id){

                                   if (/(iPhone|iPad|iPod|iOS)/i.test(navigator.userAgent)) {


   try {


      if( $("#input").val()){
                                           
                                            window.webkit.messageHandlers.collectGzhu.postMessage({body: "'"+goods_id+"'"});
                    

        }else {
                                            window.webkit.messageHandlers.collectGzhu.postMessage({body: 'toLogin'});
                  

   }


                                   }catch (e){
                                        //瀏覽器
                                        alert(e);
                                    }

//oc原生處理:

  if ([message.name isEqualToString:@"collectIsLogin"]) {

       NSDictionary * messageDict = (NSDictionary *)message.body;

        if ([messageDict[@"body"] isEqualToString:@"toLogin"]) {

            NSLog(@"登入");

        }else{

            NSLog(@"正常跳轉");

            NSLog(@"mess --- id == %@",message.body);

        }

    }

}

    3.在互動中,關於alert (單對話方塊)函式、confirm(yes/no對話方塊)函式、prompt(輸入型對話方塊)函式時,實現代理協議 WKUIDelegate ,則系統方法裡有三個對應的協議方法.大家可以進入WKUIDelegate 協議類裡面檢視.下面具體協議方法實現,也給大家粘出來,以供參考.

#pragma mark - WKUIDelegate

- (void)webViewDidClose:(WKWebView *)webView {

NSLog(@"%s", __FUNCTION__);

}

// 在JS端呼叫alert函式時,會觸發此代理方法。

// JS端呼叫alert時所傳的資料可以通過message拿到

// 在原生得到結果後,需要回調JS,是通過completionHandler回撥

- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {

NSLog(@"%s", __FUNCTION__);

UIAlertController *alert = [UIAlertControlleralertControllerWithTitle:@"alert"message:@"JS呼叫alert"preferredStyle:UIAlertControllerStyleAlert];

    [alert addAction:[UIAlertActionactionWithTitle:@"確定"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction * _Nonnull action) {

        completionHandler();

    }]];

    [selfpresentViewController:alert animated:YEScompletion:NULL];

    NSLog(@"%@", message);

}

// JS端呼叫confirm函式時,會觸發此方法

// 通過message可以拿到JS端所傳的資料

// 在iOS端顯示原生alert得到YES/NO後

// 通過completionHandler回撥給JS端

- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler {

NSLog(@"%s", __FUNCTION__);

UIAlertController *alert = [UIAlertControlleralertControllerWithTitle:@"confirm"message:@"JS呼叫confirm"preferredStyle:UIAlertControllerStyleAlert];

    [alert addAction:[UIAlertActionactionWithTitle:@"確定"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction * _Nonnull action) {

        completionHandler(YES);

    }]];

    [alert addAction:[UIAlertActionactionWithTitle:@"取消"style:UIAlertActionStyleCancelhandler:^(UIAlertAction * _Nonnull action) {

        completionHandler(NO);

    }]];

    [selfpresentViewController:alert animated:YEScompletion:NULL];

    NSLog(@"%@", message);

}

// JS端呼叫prompt函式時,會觸發此方法

// 要求輸入一段文字

// 在原生輸入得到文字內容後,通過completionHandler回撥給JS

- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * __nullable result))completionHandler {

NSLog(@"%s", __FUNCTION__);

    NSLog(@"%@", prompt);

UIAlertController *alert = [UIAlertControlleralertControllerWithTitle:@"textinput"message:@"JS呼叫輸入框"preferredStyle:UIAlertControllerStyleAlert];

    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {

        textField.textColor = [UIColor redColor];

    }];

    [alert addAction:[UIAlertActionactionWithTitle:@"確定"style:UIAlertActionStyleDefaulthandler:^(UIAlertAction * _Nonnull action) {

        completionHandler([[alert.textFields lastObject] text]);

    }]];

    [selfpresentViewController:alert animated:YEScompletion:NULL];

}