iOS js与WKWebView交互

2018-01-25  本文已影响152人  vision_colion

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

 使用场景: 浏览web页面商品,点击查看详情,进入原生界面浏览商品详情.
#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];
    //记得实现对应协议,不然方法不会实现.
    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  =[NSString stringWithFormat:@"sendKey('%@')",jsUserId];
    [self.webView evaluateJavaScript: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 = [UIAlertController alertControllerWithTitle:@"alert" message:@"JS调用alert" preferredStyle:UIAlertControllerStyleAlert];
    [alert addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }]];
    [self presentViewController:alert animated:YES completion: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 = [UIAlertController alertControllerWithTitle:@"confirm" message:@"JS调用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端调用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 = [UIAlertController alertControllerWithTitle:@"textinput" message:@"JS调用输入框" 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];
}

转自ios js与oc原生WKWebView方法注入及交互传值

上一篇下一篇

猜你喜欢

热点阅读