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

    转载:https://www.jianshu.com/p/253e76a74b38

    用普通的UIWebView和JS交互 大概核心代码是这样的

    - (void)setupWebView{
      self.webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 20, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height)];
      self.webView.delegate = self;
      NSString* path = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
      NSURL* url = [NSURL fileURLWithPath:path];
      NSURLRequest* request = [NSURLRequest requestWithURL:url] ;
      [self.webView loadRequest:request];
      [self.view addSubview:self.webView];
    }
    

    代理方法

    - (void)webViewDidFinishLoad:(UIWebView *)webView {
       //获取js上下文
       self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];  
       //注入JS对象名称 "JSObjec"
       self.jsContext[@"JSObjec"] = self;
       self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
            context.exception = exceptionValue;
            NSLog(@"异常信息:%@", exceptionValue);
        };
    }
    

    想调用的OC方法

    - (void)getCall:(NSString *)callString{
       NSLog(@"Get----:%@", callString);
       //此处填写相应的逻辑代码
    }
    

    然后JS代码

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    </head>
    <body>
    <div style="margin-top: 20px">
    <h2>JS与OC交互</h2>
    <input type="button" value="唤起本地方法(call)" onclick="JSObjec.call()">
    </div>
    <script>
         
    var call = function()
    {
        var callInfo = JSON.stringify("www.jianshu.com");//此处参数可自定义
            JSObjec.getCall(callInfo);
    }
    </script>
    </body>
    </html>
    

    接下来是WKWebView的核心代码

    需要导入头文件 代理

    #import <WebKit/WebKit.h>
    #import <JavaScriptCore/JavaScriptCore.h>
    @interface ViewController ()<WKNavigationDelegate,WKScriptMessageHandler>
    @property (nonatomic,strong) WKWebView *webView;
    
    - (void)setupWKWebView{
        WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
        // 设置偏好设置
        config.preferences = [[WKPreferences alloc] init];
        // 默认为0
        config.preferences.minimumFontSize = 10;
        // 默认认为YES
        config.preferences.javaScriptEnabled = YES;
        // 在iOS上默认为NO,表示不能自动通过窗口打开
        config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
        config.processPool = [[WKProcessPool alloc] init];
        config.userContentController = [[WKUserContentController alloc] init];
        //注意在这里注入JS对象名称 "JSObjec"
        [config.userContentController addScriptMessageHandler:self name:@"JSObjec"];
    
        self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds configuration:config];
        self.webView.navigationDelegate = self;
        [self.view addSubview:self.webView];
    
        NSURL *path = [[NSBundle mainBundle] URLForResource:@"index" withExtension:@"html"];
        [self.webView loadRequest:[NSURLRequest requestWithURL:path]];
    }
    
    - (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
        NSLog(@"%@",message.body);//message.body这里面内容是js里传过来的参数
    //message.name这个是注入的JS对象名称 "JSObjec" 
        if ([message.name isEqualToString:@"JSObjec"]) {
            // 打印所传过来的参数,只支持NSNumber, NSString, NSDate, NSArray,
            // NSDictionary, and NSNull类型
            // 此处填写相应的逻辑代码
        }
    }
    

    然后JS代码

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset="UTF-8">
    </head>
    <body>
    <div style="margin-top: 20px">
    <h2>JS与OC交互</h2>
    <input type="button" value="唤起本地方法(call)" onclick="JSObjec.call()">
    </div>
    <script>
         
    var call = function()
    {
        var callInfo = JSON.stringify("www.jianshu.com");//此处参数可自定义
      //这里的内容差不多全部一样 只是调用的方法有区别 一定要注意区分
      //这个是用UIWebView时调用的方法 JSObjec.getCall(callInfo);
      //下面是用WKWebView调用的方法
        window.webkit.messageHandlers.JSObjec.postMessage(callInfo);
    }
    </script>
    </body>
    </html>
    

    好了 希望这篇总结能帮助到大家。

    后续补充

    //从OC中获取到一些数据后存入JS
    NSString *sendToken = [NSString stringWithFormat:@"localStorage.setItem("accessToken",'%@');",SecurityToken];
    
    //WKUserScriptInjectionTimeAtDocumentStart JS加载前执行
    //WKUserScriptInjectionTimeAtDocumentEnd JS加载后执行
    //injectionTime配置不要写错  forMainFrameOnly  NO(全局窗口) YES(只限主窗口)
    WKUserScript *sendTokenScript = [[WKUserScript alloc]initWithSource:sendToken injectionTime:WKUserScriptInjectionTimeAtDocumentStart forMainFrameOnly:NO];
    
    //注入JS
    [config.userContentController addUserScript:sendTokenScript];



    作者:波妞和酱豆子
    链接:https://www.jianshu.com/p/253e76a74b38
    来源:简书
    著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。

  • 相关阅读:
    C语言中的异常处理
    silverlight与游戏中的人工智能基本追逐与闪躲(二)
    具有3D旋转效果的图片组的一种实现
    [转]ColorMatrixFilter颜色矩阵滤镜
    silverlight effect的一些整理
    silverlight练习之利用DridSplitter和Drid,Line制作可变行列宽度的表格
    str_replace函数详解
    《JavaScript高级程序设计(第2版)》
    FCKEditor+jQuery+PHP实现分页
    如何书写高效、可维护、组件化的CSS。
  • 原文地址:https://www.cnblogs.com/lrr0618/p/13213425.html
Copyright © 2011-2022 走看看