zoukankan      html  css  js  c++  java
  • webView和js交互

    与 js 交互

    OC 调用 JS

    // 执行 js
    - (void)webViewDidFinishLoad:(UIWebView *)webView {
        NSString *title = [webView stringByEvaluatingJavaScriptFromString:@"document.title;"];
        NSLog(@"%@", title);
    
        [webView stringByEvaluatingJavaScriptFromString:@"clickme();"];
    }
    

    JS 调用 OC

    准备代码

    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
        NSLog(@"%@", request.URL);
    
        return YES;
    }
    

    在 OC 中,如果代理方法返回 BOOL 类型,返回 YES 会正常执行

    解释自定义协议

    href="myfunc:///showMessage:/周末一起玩吧:D"
    
    调用 OC 中的方法 `showMessage:` 显示内容 `郊游怎么样:D`
    

    代码实现

    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
        NSLog(@"%@", request.URL.scheme);
    
        if ([request.URL.scheme isEqualToString:@"myfunc"]) {
    
            NSLog(@"%@", request.URL.pathComponents);
    
            NSArray *components = request.URL.pathComponents;
    
            NSString *funcName = components[1];
            NSString *param = components[2];
    
            SEL func = NSSelectorFromString(funcName);
            [self performSelector:func withObject:param];
        }
    
        return YES;
    }
    

    代码细节

    - (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
    
        NSLog(@"%@", request.URL.scheme);
    
        if ([request.URL.scheme isEqualToString:@"myfunc"]) {
    
            NSLog(@"%@", request.URL.pathComponents);
    
            NSArray *components = request.URL.pathComponents;
            if (components.count != 3) {
                return NO;
            }
    
            NSString *funcName = components[1];
            NSString *param = components[2];
    
            SEL func = NSSelectorFromString(funcName);
    
            if ([self respondsToSelector:func]) {
    #pragma clang diagnostic push
    #pragma clang diagnostic ignored "-Warc-performSelector-leaks"
                [self performSelector:func withObject:param];
    #pragma clang diagnostic pop
            }
    
            return NO;
        }
    
        return YES;
    }
  • 相关阅读:
    【科普】.NET 泛型
    吐槽,青岛科技大学真他妈操蛋
    c# 数组和集合精讲
    c# System.Text.Json 精讲
    .NET 5的System.Text.Json的JsonDocument类讲解
    c#中Array,ArrayList 与List<T>的区别、共性与转换
    代码是怎么运行的?
    .NET6使用DOCFX根据注释自动生成开发文档
    spring通过注解注册bean的方式+spring生命周期
    莫比乌斯反演
  • 原文地址:https://www.cnblogs.com/Ruby-Hua/p/5249387.html
Copyright © 2011-2022 走看看