js和OC交互

0.html+js

0.1html 代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
    <style>
        #colordv{
            width: 100px;
            height: 100px;
            margin: auto;
            background-color:red;
        }
    .icon{
        
    }
    </style>
</head>
<body>

<div id="colordv" class="icon"></div>

<script src="1.js"></script>

</body>
</html>

0.2js代码

//uiwebview
function asyncAlert(text) {
    setTimeout(function(){
              alert('这是来自网页的弹窗:' + text);
               },0);
    var obj = document.getElementById('colordv');
    obj.sendText('这是来自网页的消息',obj);
}

//wkwebview
window.onload = function(){
    var obj = document.getElementById('colordv');
    obj.onclick = function(){
        shareList(['123','333','kkk']);
        this.style.backgroundColor = "pink";
    }
}


function shareList(texts){
    window.webkit.messageHandlers.shareList.postMessage(texts);
}

function wkAsyncAlert(text) {
    setTimeout(function(){
               alert('这是来自网页的弹窗:' + text);
               },0);
    return '返回结果';
}

1.uiwebview

1.0初始化代码

    UIWebView *webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
    [self.view addSubview:webView];
    webView.delegate = self;
    NSString *path = [[NSBundle mainBundle] pathForResource:@"1.html" ofType:nil];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
    [webView loadRequest:request];

1.1在代理方法中-(void)webViewDidFinishLoad:(UIWebView *)webView;

JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    JSValue *obj = context[@"colordv"];
    
    //设置网页元素的方法,接收网页元素发送的消息
    obj[@"sendText"] = ^(){
        NSArray *args = [JSContext currentArguments];
        NSLog(@"%@",args.firstObject);
        
        JSValue *btn = args.lastObject;
        btn[@"style"][@"backgroundColor"]=@"pink";
    };
//    __weak typeof(webView) weakView = webView;
    //设置网页元素的方法,并向网页发送消息
    obj[@"onclick"] = ^(){
        NSString *text = @"hello world";
        NSString *jsStr = [NSString stringWithFormat:@"asyncAlert('%@')",text];
        //oc 调用js的方法1:
        [[JSContext currentContext] evaluateScript:jsStr];
        
        //oc 调用js的方法2:
//        [[JSContext currentContext][@"asyncAlert"] callWithArguments:@[@"hahaha"]];
        
        //oc 调用js的方法3:必需主线程调用
//        dispatch_async(dispatch_get_main_queue(), ^{
//            __strong typeof(weakView) wv = weakView;
//             [wv stringByEvaluatingJavaScriptFromString:jsStr];
//        });
    };

总结:

1.js调用oc的方法大致就是,js中声明方法,使用方法,oc中实现方法

2.oc调用js的方法大致就是调用方法:[webview evaluateScript:@"xxxx"];

 

2.wkwebview

2.0初始化代码

    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    WKPreferences *prefences = [[WKPreferences alloc] init];
    prefences.javaScriptCanOpenWindowsAutomatically = YES;
    prefences.minimumFontSize = 30;
    config.preferences = prefences;
    WKWebView *webview = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
    [self.view addSubview:webview];
    webview.UIDelegate = self;
    _wkWebView = webview;
    
    NSString *path = [[NSBundle mainBundle] pathForResource:@"1.html" ofType:nil];
    NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL fileURLWithPath:path]];
    [_wkWebView loadRequest:request];
    
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [self.view addSubview:btn];
    btn.backgroundColor = [UIColor redColor];
    btn.frame = CGRectMake(100, 100, 80, 40);
    [btn setTitle:@"dada" forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(dadaClick:) forControlEvents:UIControlEventTouchUpInside];

说明:在wk中,js和oc的消息传递,大都是通过config来完成,需要通过config来添加或者删除消息

-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [_wkWebView.configuration.userContentController addScriptMessageHandler:self name:@"shareList"];
}

-(void)viewWillDisappear:(BOOL)animated{
    [super viewWillDisappear:animated];
    [_wkWebView.configuration.userContentController removeScriptMessageHandlerForName:@"shareList"];
}

2.1js向oc发消息

此时需要修改js的代码,格式为:

function shareList(texts){
    window.webkit.messageHandlers.shareList.postMessage(texts);
}

oc中通过config接收消息,需要实现WKScriptMessageHandler这个协议

//js调用oc
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{
    if ([message.name isEqualToString:@"shareList"]) {
        NSLog(@"%@",message.body);
    }
}

2.2oc向js发消息

大致还是还是通过evaluateJavaScript这个方法,但是细节发生了变化

-(IBAction)dadaClick:(id)sender{
    NSString *js = [NSString stringWithFormat:@"wkAsyncAlert('%@')",@"wkwebview"];
    [_wkWebView evaluateJavaScript:js
                 completionHandler:^(id _Nullable ret, NSError * _Nullable error) {
                     //ret为js执行的返回结果
                     NSLog(@"ret:%@",ret);
                     //error为js执行出错时的反馈
                     NSLog(@"err:%@",error);
                 }];
}

2.3js调用alert等ui事件时,需要实现WKUIDelegate的方法,否则没有效果,例如

//js调用alert
-(void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    NSLog(@"message:%@",message);
    completionHandler();//必需调用,表示操作完成
}

 

转载于:https://my.oschina.net/u/3697347/blog/2988686

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值