js 调用OC


//
//  ViewController.m
//  wkweb
//
//  Created by 柏超曾 on 2017/8/29.
//  Copyright © 2017年 柏超曾. All rights reserved.
//

#import "ViewController.h"
#import <WebKit/WebKit.h>


@interface ViewController ()<WKUIDelegate,WKNavigationDelegate,NSURLConnectionDataDelegate,WKScriptMessageHandler>
//@interface ViewController ()<UIWebViewDelegate>

@property (nonatomic, strong) WKWebView *webView; ///< WKWebView

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view, typically from a nib.
    

    //    [self loadWebView]; // 加载测试
    NSURL *url = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
    NSURLRequest *urlRequest = [NSURLRequest requestWithURL:url];
    [self.webView loadRequest:urlRequest]; // 加载页面
}
    
    


#pragma mark - get方法
- (WKWebView *)webView {
    if (_webView == nil) {
        // js配置
        WKUserContentController *userContentController = [[WKUserContentController alloc] init];
        [userContentController addScriptMessageHandler:self name:@"jsCallOC"];
        // js注入,注入一个alert方法,页面加载完毕弹出一个对话框。
        NSString *javaScriptSource = @"alert(\"WKUserScript注入js\");";
        WKUserScript *userScript = [[WKUserScript alloc] initWithSource:javaScriptSource injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];// forMainFrameOnly:NO(全局窗口),yes(只限主窗口)
        [userContentController addUserScript:userScript];
        
        // WKWebView的配置
        WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
        configuration.userContentController = userContentController;
        
        // 显示WKWebView
        _webView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];
        _webView.UIDelegate = self; // 设置WKUIDelegate代理
        [self.view addSubview:_webView];
    }
    return _webView;
}


#pragma mark - WKScriptMessageHandler
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"方法名:%@", message.name);
    NSLog(@"参数:%@", message.body);
    // 方法名
    NSString *methods = [NSString stringWithFormat:@"%@:", message.name];
    SEL selector = NSSelectorFromString(methods);
    // 调用方法
    if ([self respondsToSelector:selector]) {
        [self performSelector:selector withObject:message.body];
    } else {
        NSLog(@"未实行方法:%@", methods);
    }
}

#pragma mark js调OC
- (void)jsCallOC:(id)body {
    if ([body isKindOfClass:[NSDictionary class]]) {
        NSDictionary *dict = (NSDictionary *)body;
        // oc调用js代码
        NSString *jsStr = [NSString stringWithFormat:@"ocCallJS('%@')", [dict objectForKey:@"data"]];
        [self.webView evaluateJavaScript:jsStr completionHandler:^(id _Nullable data, NSError * _Nullable error) {
            if (error) {
                NSLog(@"错误:%@", error.localizedDescription);
            }
        }];
    }
}



//#pragma mark - UIWebViewDelegate
//- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType
//{
//    NSURL * url = [request URL];
//    if ([[url scheme] isEqualToString:@"firstclick"]) {
//        NSArray *params =[url.query componentsSeparatedByString:@"&"];
//        
//        NSMutableDictionary *tempDic = [NSMutableDictionary dictionary];
//        for (NSString *paramStr in params) {
//            NSArray *dicArray = [paramStr componentsSeparatedByString:@"="];
//            if (dicArray.count > 1) {
//                NSString *decodeValue = [dicArray[1] stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
//                [tempDic setObject:decodeValue forKey:dicArray[0]];
//            }
//        }
//        UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"方式一" message:@"这是OC原生的弹出窗" delegate:self cancelButtonTitle:@"收到" otherButtonTitles:nil];
//        [alertView show];
//        NSLog(@"tempDic:%@",tempDic);
//        return NO;
//    }
//    
//    return YES;
//}



//- (void)webView:(WKWebView *)webView didReceiveAuthenticationChallenge:(NSURLAuthenticationChallenge *)challenge completionHandler:(void (^)(NSURLSessionAuthChallengeDisposition disposition, NSURLCredential * _Nullable credential))completionHandler{
//    
//    if ([challenge.protectionSpace.authenticationMethod isEqualToString:NSURLAuthenticationMethodServerTrust]) {
//        
//        NSURLCredential *credential = [[NSURLCredential alloc]initWithTrust:challenge.protectionSpace.serverTrust];
//        
//        completionHandler(NSURLSessionAuthChallengeUseCredential,credential);
//        
//    }
//    
//    
//    
//}
//- (nullable WKWebView *)webView:(WKWebView *)webView createWebViewWithConfiguration:(WKWebViewConfiguration *)configuration forNavigationAction:(WKNavigationAction *)navigationAction windowFeatures:(WKWindowFeatures *)windowFeatures{
//    
//    
//    if (!navigationAction.targetFrame.isMainFrame) {
//        [self.wkWebView loadRequest:navigationAction.request];
//    }
//    
//    return nil;
//}





- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
    
}


@end



<!doctype html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=utf-8">
            <meta name="viewport" content="width=device-width, maximum-scale=2, minimum-scale=1, user-scalable=no">
                <title>首页</title>
                <style type="text/css">
                    *{
                        margin:0;
                        padding: 0;
                    }
                body,html{
                    height: 100%;
                    width: 100%;
                }
                section{
                    height: 100%;
                    width: 100%;
                    text-align:center;
                }
                .div{
                    float: left;
                    position: relative;
                    left: 50%;
                    top: 30%;
                    margin-left: -113px;
                    margin-top: -20px;
                }
                </style>
                <script>
                    // $解析器
                    function $ (ele) {
                        return document.querySelector(ele);
                    };
                
                // 点击确定按钮
                function onClickButton() {
                    // 复杂数据
                    var list = [1,2,3];
<!--                    var dict = {"name":"阳君", "qq":"937447974", "data":input.value, "list":list};-->

var dict = {"name":"阳君", "qq":"937447974"};

                alert(dict);
                    // JS通知WKWebView
                    window.webkit.messageHandlers.jsCallOC.postMessage(dict);
                }
                
                // WKWebView调用JS
                function ocCallJS(params) {
                    show.innerHTML = params;
                }
                
                // alert对话框
                function ale() {
                    alert("这是一个警告对话框!");
                }
                
                // confirm选择框
                function firm() {
                    if(confirm("去百度看看?")) {
                        alert("你选择了去!");
                    } else {
                        alert("你选择了不去!");
                    }
                }
                
                // prompt输入框
                function prom() {
                    var result = prompt("演示一个带输入的对话框", "这里输入你的信息");
                    if(result) {
                        alert("谢谢使用,你输入的是:" + result)
                    }
                }
                </script>
    </head>
    
    <body >
        <section>
            <div class="div">
                <input type="text" id="input" style="width:150px;line-height:30px">
                    <a style="margin-left:10px;width:50px;line-height:30px;display:inline-block;background-color:blue;color:#fff;text-align:center;" id="button" >确定</a>
                    <br>
                    <span id="show" style="display:inline-block;width:100%;text-align:left;font-size:18px;font-family:'微软雅黑';color:#000;margin-top:20px;" ></span>
                    <br><br>
                    <input type="submit" value="警告框" onclick="ale()" />
                    <input type="submit" value="选择框" style="margin-left:20px;" onclick="firm()" />
                    <input type="submit" value="输入框" style="margin-left:20px;" onclick="prom()" />
                    </div>
        </section>
        <script type="text/javascript">
            // 界面渲染完毕执行
            var input = $('#input'),
            button = $('#button'),
            show = $('#show');
            // 按钮监听
            button.addEventListener('click', onClickButton);
            </script>
    </body>
</html>

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容