zoukankan      html  css  js  c++  java
  • WKWebView与Js交互

    首先打开webstorm,将最下面h5拷贝到html中。然后导入工程

    #define kMessageHandlerName @"mymobile"

    1.创建配置类

    - (WKWebView *)webView{
    if (!_webView) {

    WKWebViewConfiguration *config =[[WKWebViewConfiguration alloc]init];

    config.preferences.javaScriptEnabled = YES;
    /** 默认是不能通过JS自动打开窗口的,必须通过用户交互才能打开 */
    config.preferences.javaScriptCanOpenWindowsAutomatically = YES;
    _webView = [[WKWebView alloc]initWithFrame:self.view.bounds configuration:config];

    _webView.frame = CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height);

    _webView.allowsBackForwardNavigationGestures = YES;//打开左划回退功能
    _webView.navigationDelegate = self;
    _webView.UIDelegate = self;
    _webView.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:_webView];

    }

    return _webView;

    }

    2.加载H5页面

    NSURL *path = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
    [self.webView loadRequest:[NSURLRequest requestWithURL:path]];

    3 注入对象名称 kMessageHandlerName

    - (void)viewWillAppear:(BOOL)animated{
            [super viewWillAppear:animated];
            [self.webView.configuration.userContentController addScriptMessageHandler:self name:kMessageHandlerName];
    }

    - (void)viewDidDisappear:(BOOL)animated{
         [super viewDidDisappear:animated];
         [self.webView.configuration.userContentController removeScriptMessageHandlerForName:kMessageHandlerName];
    }

    /**代理方法
    JS通过mymobile发送数据到iOS端时,在代理中接收
    var message = {"method":"call","args":"let go"};
    window.webkit.messageHandlers.mymobile(注:这里是注入的对象名).postMessage(message);
    */
    - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message{

                NSDictionary *dic = message.body;

               NSString *method = dic[@"method"];

              if ([method isEqualToString:@"call"]) {

             [self call];
          }

               NSLog(@"dic = %@", dic);
    }

    - (void)call{


    UIAlertController *sheet = [UIAlertController alertControllerWithTitle:nil message:nil preferredStyle:UIAlertControllerStyleActionSheet];
    [sheet addAction:[UIAlertAction actionWithTitle:@"拍照" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
    //调用js
    NSString *js = [NSString stringWithFormat:@"gotoCall()"];
    [self.webView evaluateJavaScript:js completionHandler:nil];


         }]];

         [sheet addAction:[UIAlertAction actionWithTitle:@"不要点我" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {


        }]];
        [sheet addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil]];
        [self presentViewController:sheet animated:YES completion:nil];

    }

    /**  在JS端调用alert函数时,会触发此代理方法(确认框) */

    - (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{


          UIAlertController *alertVC = [UIAlertController alertControllerWithTitle:nil message:message preferredStyle:UIAlertControllerStyleAlert];
          [alertVC addAction:[UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:nil]];
          [self presentViewController:alertVC animated:YES completion:nil];

          completionHandler();
    }

    <html>
    <head lang="en">
    <meta charset="UTF-8">
    <title></title>
    <style type="text/css">
    *{
    font-size: 40px;
    }
    </style>
    </head>

    <body>

    <div style=" margin-top: 150px">

    <p></p>

    <div>
    <button id="call">拍照</button>
    </div>

    <script type="text/javascript">

    call.onclick = function() {
    var message = {"method":"call","args":"let go"};
    window.webkit.messageHandlers.mymobile.postMessage(message);
    };


    function gotoCall(){
    alert('调用了OC中的alert')
    }

    </script>

    </body>

    </html>

  • 相关阅读:
    jQuery操作Table学习总结[转]
    SQL语句中的单引号处理以及模糊查询
    正则表达式实现将html文本转换为纯文本格式(将html字符串转换为纯文本方法)
    ASP.NET中使用UpdatePanel实现局部异步刷新方法和攻略(转)
    Response.Redirect在新窗口打开(转载)
    position属性absolute与relative 的区别
    下载文件
    gridveiw的使用
    MarkDown和流程图诠释你的代码
    git使用笔记
  • 原文地址:https://www.cnblogs.com/xsiOS/p/5040237.html
Copyright © 2011-2022 走看看