iOS js與WKWebView交互

1.瀏覽web頁面,點(diǎn)擊某個方法,并傳值給oc原生,原生界面做出響應(yīng).

 使用場景: 瀏覽web頁面商品,點(diǎn)擊查看詳情,進(jìn)入原生界面瀏覽商品詳情.
#import <JavaScriptCore/JavaScriptCore.h>
#import <WebKit/WebKit.h>

@interface ViewController ()<WKNavigationDelegate,UIScrollViewDelegate,WKUIDelegate,WKScriptMessageHandler>
@property (nonatomic, strong) WKWebView *webView;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view .backgroundColor =[UIColor whiteColor];
    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    config.preferences = [[WKPreferences alloc] init];
    config.preferences.minimumFontSize = 10;
    config.preferences.javaScriptEnabled = YES;
    config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
    config.userContentController = [[WKUserContentController alloc] init];
    config.processPool = [[WKProcessPool alloc] init];
    self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    //記得實(shí)現(xiàn)對應(yīng)協(xié)議,不然方法不會實(shí)現(xiàn).
    self.webView.UIDelegate = self;
    self.webView.navigationDelegate =self;
    [self.view addSubview:self.webView];
    [self.webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://192.168.1.188/index1.html"]]];

    // **************** 此處劃重點(diǎn) **************** //
    //添加注入js方法, oc與js端對應(yīng)實(shí)現(xiàn)
    [config.userContentController addScriptMessageHandler:self name:@"collectSendKey"];
    [config.userContentController addScriptMessageHandler:self name:@"collectIsLogin"];

    //js端代碼實(shí)現(xiàn)實(shí)例(此處為js端實(shí)現(xiàn)代碼給大家粘出來示范的!!!):
    //window.webkit.messageHandlers.collectSendKey.postMessage({body: 'goodsId=1212'});
}

#pragma mark - WKScriptMessageHandler
//實(shí)現(xiàn)js注入方法的協(xié)議方法
- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message {
    //找到對應(yīng)js端的方法名,獲取messge.body
    if ([message.name isEqualToString:@"collectSendKey"]) {
        NSLog(@"%@", message.body);
    }
}

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

 使用場景: 瀏覽web頁面商品,加入購物車,js通過oc原生傳遞過去的userId是否為空,來判斷當(dāng)前app是否登錄,未登錄,跳轉(zhuǎn)原生界面登錄,已登錄,則直接加入購物車
#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騙我文化低,反正,咱們把值傳給他,根據(jù)雙方商量好的邏輯,給出判斷,如果正常,那就ok了.
    NSString * jsStr  =[NSString stringWithFormat:@"sendKey('%@')",jsUserId];
    [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
  //此處可以打印error.
    }];

   //js端獲取傳遞值代碼實(shí)現(xiàn)實(shí)例(此處為js端實(shí)現(xiàn)代碼給大家粘出來示范的!!!):
    //function sendKey(user_id){
           $("#input").val(user_id);
       }
}

//依然是這個協(xié)議方法,獲取注入方法名對象,獲取js返回的狀態(tài)值.
#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController
      didReceiveScriptMessage:(WKScriptMessage *)message {
//js端判斷如果userId為空,則返回字符串@"toLogin"  ,或者返回其它值.  js端代碼實(shí)現(xiàn)實(shí)例(此處為js端實(shí)現(xiàn)代碼給大家粘出來示范的!!!):
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(@"正常跳轉(zhuǎn)");
            NSLog(@"mess --- id == %@",message.body);
        }
    }
}

3.在交互中,關(guān)于alert (單對話框)函數(shù)、confirm(yes/no對話框)函數(shù)、prompt(輸入型對話框)函數(shù)時,實(shí)現(xiàn)代理協(xié)議 WKUIDelegate ,則系統(tǒng)方法里有三個對應(yīng)的協(xié)議方法.大家可以進(jìn)入WKUIDelegate 協(xié)議類里面查看.

#pragma mark - WKUIDelegate
- (void)webViewDidClose:(WKWebView *)webView {
    NSLog(@"%s", __FUNCTION__);
}

// 在JS端調(diào)用alert函數(shù)時,會觸發(fā)此代理方法。
// JS端調(diào)用alert時所傳的數(shù)據(jù)可以通過message拿到
// 在原生得到結(jié)果后,需要回調(diào)JS,是通過completionHandler回調(diào)
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler {
    NSLog(@"%s", __FUNCTION__);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"alert" message:@"JS調(diào)用alert" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    [self presentViewController:alert animated:YES completion:NULL];
    NSLog(@"%@", message);
}

// JS端調(diào)用confirm函數(shù)時,會觸發(fā)此方法
// 通過message可以拿到JS端所傳的數(shù)據(jù)
// 在iOS端顯示原生alert得到Y(jié)ES/NO后
// 通過completionHandler回調(diào)給JS端
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler {
    NSLog(@"%s", __FUNCTION__);
    UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"confirm" message:@"JS調(diào)用confirm" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }]];
    [alert addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }]];
    [self presentViewController:alert animated:YES completion:NULL];   
    NSLog(@"%@", message);
}

// JS端調(diào)用prompt函數(shù)時,會觸發(fā)此方法
// 要求輸入一段文本
// 在原生輸入得到文本內(nèi)容后,通過completionHandler回調(diào)給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 = [UIAlertController alertControllerWithTitle:@"textinput" message:@"JS調(diào)用輸入框" preferredStyle:UIAlertControllerStyleAlert];
    [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.textColor = [UIColor redColor];
    }];  
    [alert addAction:[UIAlertAction actionWithTitle:@"確定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler([[alert.textFields lastObject] text]);
    }]];    
    [self presentViewController:alert animated:YES completion:NULL];
}

轉(zhuǎn)自ios js與oc原生WKWebView方法注入及交互傳值

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。