打开APP
userphoto
未登录

开通VIP,畅享免费电子书等14项超值服

开通VIP
ios js与oc原生WKWebView方法注入及交互传值

    上篇文章中,我们整理了关于WKWebView的详细使用,包含进度条、获取web title等等内容,这篇文章我们整理下,项目中,我们可能使用到的oc 与 js 原生交互场景下的使用.如有兴趣,可加入oneTeam技术交流群: 234713941 ,本人不才小白,多多指教!

     原生加载控件使用的是WKWebView.


     1.浏览web页面,点击某个方法,并传值给oc原生,原生界面做出响应.

     使用场景: 浏览web页面商品,点击查看详情,进入原生界面浏览商品详情.

     直接看代码:

#import <JavaScriptCore/JavaScriptCore.h>

#import <WebKit/WebKit.h>

@interface ViewController ()<WKNavigationDelegate,UIScrollViewDelegate,WKUIDelegate,WKScriptMessageHandler>


@property (nonatomicstrongWKWebView *webView;


@end


@implementation ViewController


- (void)viewDidLoad {

    [super viewDidLoad];

    self.view .backgroundColor =[UIColor whiteColor];

    

    WKWebViewConfiguration *config = [[WKWebViewConfiguration allocinit];

    config.preferences = [[WKPreferences allocinit];

    config.preferences.minimumFontSize = 10;

    config.preferences.javaScriptEnabled = YES;

    config.preferences.javaScriptCanOpenWindowsAutomatically = NO;

    config.userContentController = [[WKUserContentController allocinit];

    config.processPool = [[WKProcessPool allocinit];

    self.webView = [[WKWebView allocinitWithFrame:self.view.bounds

                                      configuration:config];

    //记得实现对应协议,不然方法不会实现.

    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"]]];

    

    // **************** 此处划重点 **************** //

    //添加注入js方法, oc与js端对应实现

    [config.userContentController addScriptMessageHandler:self name:@"collectSendKey"];

    [config.userContentController addScriptMessageHandler:self name:@"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:(nullableNSString *)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 = [UIColorredColor];

    }];

    

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

        completionHandler([[alert.textFieldslastObject] text]);

    }]];

    

    [selfpresentViewController:alert animated:YEScompletion:NULL];

}



     


本站仅提供存储服务,所有内容均由用户发布,如发现有害或侵权内容,请点击举报
打开APP,阅读全文并永久保存 查看更多类似文章
猜你喜欢
类似文章
【热】打开小程序,算一算2024你的财运
WKWebView与JS交互之实战技巧介绍
Swift-WKWebView与JavaScript的细节,H5页面跳转原生界面
WKWebView在实际开发中的使用汇总
iOS开发 WKWebView学习使用
WKWebView特性及使用
使用WKWebView替换UIWebView
更多类似文章 >>
生活服务
热点新闻
分享 收藏 导长图 关注 下载文章
绑定账号成功
后续可登录账号畅享VIP特权!
如果VIP功能使用有故障,
可点击这里联系客服!

联系客服