美文网首页
iOS UIWebView的基本使用及与JS交互

iOS UIWebView的基本使用及与JS交互

作者: 尤先森 | 来源:发表于2019-03-24 22:36 被阅读0次

    [图片上传失败...(image-1189b9-1553438203049)]

    UIWebView

    • 基本使用
    @interface ViewController ()<UIWebViewDelegate>
    @property (nonatomic, strong) UIWebView *webView;
    @end
    
    @implementation ViewController
    
    - (void)viewDidLoad {
        [super viewDidLoad];
     
        self.webView = [[UIWebView alloc] initWithFrame:self.view.bounds];
        self.webView.delegate = self;
        [self.view addSubview:self.webView];
        
        NSURL *url = [[NSBundle mainBundle] URLForResource:@"index.html" withExtension:nil];
        NSURLRequest *reqeust = [NSURLRequest requestWithURL:url];
        [self.webView loadRequest:reqeust];
    }
    #pragma mark - UIWebViewDelegate
    // 加载所有请求数据,以及控制是否加载
    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
        NSLog(@"加载所有请求数据,以及控制是否加载,可以进行一些操作");
        return YES;
    }
    // 开始加载
    - (void)webViewDidStartLoad:(UIWebView *)webView{
        NSLog(@"开始加载");
    }
    // 加载完成
    - (void)webViewDidFinishLoad:(UIWebView *)webView{
        NSLog(@"加载完成");
    }
    // 加载失败
    - (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
        NSLog(@"加载失败,原因:%@",error);
    }
    
    
    UIWebView与JS交互
    • 方案一:stringByEvaluatingJavaScriptFromString
      这里有一份简单的HTML,一共三个方法。
      1.普通弹窗。
      2.返回了一个字符串。
      3.弹窗内容为数组,但是HTML并没有声明arr。
    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>UIWebView与JS交互</title>
        <script>
            function showAlert(name){
                alert(name);
            }
            function returnStr(){
                return '这是要返回给OC的';
            }
            function showAlertWithArr(){
                alert(arr[0]+arr[1]+arr[2]);
            }
        </script>
    </head>
    <body>
        <input type="button" value="弹框" onclick="showAlert('hello JS')">
        <input type="button" value="弹数组" onclick="showAlertWithArr()">
    <br/>
    </body>
    </html>
    

    1.获取HTML标题
    webViewDidFinishLoad当web加载结束后,调用获取。

    - (void)webViewDidFinishLoad:(UIWebView *)webView{
        NSString *tittle = [webView stringByEvaluatingJavaScriptFromString:@"document.title"];
        self.title = tittle;
    }
    

    2.OC调用JS方法

    [self.webView stringByEvaluatingJavaScriptFromString:@"showAlert('我是HTML以外写的')"];
    

    那么JS方法里面的那个return是干啥的?

    NSString *str = [self.webView stringByEvaluatingJavaScriptFromString:@"returnStr()"];
    NSLog(@"%@",str);
    //输出内容
    //这是要返回给OC的
    

    3.JS调用OC
    这个比较笨拙,需要通过- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType;拦截request内容来实现,这里就不展示了。

    4.给HTML增加变量

    // 加载完成
    - (void)webViewDidFinishLoad:(UIWebView *)webView{
        [webView stringByEvaluatingJavaScriptFromString:@"var arr = ['你好','我是','外面进来的']"];
    }
    
    • 方案二 JavaScriptCore
      image.png
      入口文件
      image.png
      主要的是这三个:
    1. JSContext:Web上下文信息
    2. JSValue:JS传过来的数据类型,可以转OC类型,桥接效果
    3. JSExport

    JSContext简单使用

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>UIWebView与JS交互</title>
        <script>
            function showAlert(name){
                alert(name);
            }
            function returnStr(){
                return '这是要返回给OC的';
            }
            function showAlertWithArr(){
                alert(arr[0]+arr[1]+arr[2]);
            }
            function showDict(dict,str){
                var name = dict['name'];
                var age = dict['age'];
                alert(name + age + str);
            }
        </script>
    </head>
    <body>
        <input type="button" value="弹框" onclick="showAlert('hello JS')">
        <input type="button" value="弹数组" onclick="showAlertWithArr()">
    <br/>
    </body>
    </html>
    

    1.获取JSContext

    // 加载完成
    - (void)webViewDidFinishLoad:(UIWebView *)webView{
        //从当前webView获取javaScriptContext
        JSContext *jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    }
    

    2.拦截JS方法调用(JS调OC)

    jsContext[@"showAlert"] = ^{
        NSLog(@"拦截了JS方法调用,原本JS方法不再执行。");
    };
    

    3.获取JS方法传参

    jsContext[@"showAlert"] = ^{
        NSLog(@"拦截JS方法调用,原本JS方法不再执行。");
        //获取传参
        NSArray *array = [JSContext currentArguments];
        NSLog(@"%@",array);
    };
    

    4.OC调JS

    [jsContext evaluateScript:@"showAlert()"];
    

    5.集合类型参数传递

    NSDictionary *dict = @{@"name":@"a",@"age":@18};
    NSString *str = @"多个参数啦";
    [self.jscontext[@"showDict"]callWithArguments:@[dictc,str]];
    

    6.异常回调

    jsContext.exceptionHandler = ^(JSContext *context, JSValue *exception) {
        NSLog(@"%@",exception);
    } ;
    

    JSValue简单使用

    jsContext[@"showAlert"] = ^{
        NSLog(@"拦截JS方法调用,原本JS方法不再执行。");
        //获取传参
        NSArray *array = [JSContext currentArguments];
        JSValue *value = array[0];
        NSLog(@"%@",value);
    };
    

    JSExport简单使用(JS操作NSObject)

    1.新建一个类


    image.png image.png

    2.新的HTML

    <!DOCTYPE html>
    <html lang="en">
    <head>
        <meta charset="UTF-8">
        <title>OC与JS交互</title>
        <script>
        function JSExportTest(){
            testobj.saySomething('JS调用OC对象方法');
            alert(testobj.gets(10,10));
        }
        </script>
    </head>
    <body>
        <input type="button" value="JS调用NSObject方法" onclick="JSExportTest()">
    </body>
    </html>
    
    

    3.JSContext设置JSExportTest对象

    // 加载完成
    - (void)webViewDidFinishLoad:(UIWebView *)webView{    
        JSContext *jsContext = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
        self.jscontext = jsContext;
    
        JSExportTest *test = [JSExportTest new];
        jsContext[@"testobj"]=test;
    }
    

    4.点击HTML按钮调起JSExportTest事件

    image.png
    image.png

    相关文章

      网友评论

          本文标题:iOS UIWebView的基本使用及与JS交互

          本文链接:https://www.haomeiwen.com/subject/dekuvqtx.html