美文网首页
UIWebView和JS交互

UIWebView和JS交互

作者: zziazm | 来源:发表于2017-12-13 10:53 被阅读28次

上个项目用到UIWebView和JS的交互,这里总结一下两者之间交互的方法。
先来研究下JS调用OC的方法

拦截URL

比如html上有一个按钮,想要点击按钮调用本地方法。
在JS中点击按钮后用JS发起一个假的URL请求,然后利用webView的代理方法shouldStartLoadWithRequest来拿到这个假的URL字符串,这个字符串包含了需要调用的方法名和传入的参数。下面是HTML的代码

<!DOCTYPE html>
<html>
    <head lang="en">
        <meta charset="UTF-8">
            <title></title>
    </head>
    <body>
        <p></p>
        <div>
            <button onclick="showToast();">无参数弹框提示</button>
            <button onclick="showToastWithParameter();">有参数弹框提示</button>
            <button onclick="shareClick();">Click Me!</button>

        </div>
        <p></p>
        <script>
        function showToast() {
            window.location.href = 'test1://showToast';
        }
        
        function showToastWithParameter() {
            window.location.href = 'test1://showToastWithParameter?parama=666666';
        }
        
        
        //不使用window.location.href
        function loadURL(url) {
            var iFrame;
            iFrame = document.createElement("iframe");
            iFrame.setAttribute("src", url);
            iFrame.setAttribute("style", "display:none;");
            iFrame.setAttribute("height", "0px");
            iFrame.setAttribute("width", "0px");
            iFrame.setAttribute("frameborder", "0");
            document.body.appendChild(iFrame);
            // 发起请求后这个 iFrame 就没用了,所以把它从 dom 上移除掉
            iFrame.parentNode.removeChild(iFrame);
            iFrame = null;
        }
        function shareClick() {
            loadURL("Test2://shareClick?title=分享的标题&content=分享的内容&url=链接地址&imagePath=图片地址");
        }
        </script>
    </body>
</html>

OC代码:

- (void)viewDidLoad {
    [super viewDidLoad];
    _webView = [[UIWebView alloc] initWithFrame:[UIScreen mainScreen].bounds];
    _webView.delegate = self;
    [self.view addSubview:_webView];
    NSURL *htmlURL = [[NSBundle mainBundle] URLForResource:@"File.html" withExtension:nil];
    NSURLRequest *request = [NSURLRequest requestWithURL:htmlURL];
    [_webView loadRequest:request];
    
    
    // Do any additional setup after loading the view.
}

#pragma mark -- UIWebViewDelegate

- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
    NSString *scheme = request.URL.scheme;
    NSString *host = request.URL.host;
    NSString *query = request.URL.query;
    NSString * url = request.URL.absoluteString;
    if ([scheme isEqualToString:@"test1"]) {
        NSString *methodName = host;
        if (query) {
            methodName = [methodName stringByAppendingString:@":"];
        }
        SEL sel = NSSelectorFromString(methodName);
        NSString *parameter = [[query componentsSeparatedByString:@"="] lastObject];
        [self performSelector:sel withObject:parameter];
        return NO;
    }else if ([scheme isEqualToString:@"test2"]){//JS中的是Test2,在拦截到的url scheme全都被转化为小写。
        NSURL *url = request.URL;
        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)webViewDidStartLoad:(UIWebView *)webView{
    
}

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    
}

- (void)webView:(UIWebView *)webView didFailLoadWithError:(NSError *)error{
    
}

- (void)showToast {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"成功" message:@"JS调用OC代码成功!" delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
}

- (void)showToastWithParameter:(NSString *)parama {
    UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"成功" message:[NSString stringWithFormat:@"JS调用OC代码成功 - JS参数:%@",parama] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
    [alert show];
}

需要注意的是,在UIWebView的代理方法中拦截到的scheme会转换成小写

点击模拟器上的第一个和第二个按钮分别会调用本地的showToast和showToastWithParameter:方法。第三个按钮中没有使用
window.location.href,在别的文章中看到了下面的解释:

因为如果当前网页正使用window.location.href加载网页的同时,调用window.location.href去调用OC原生方法,会导致加载网页的操作被取消掉。
同样的,如果连续使用window.location.href执行两次OC原生调用,也有可能导致第一次的操作被取消掉。所以我们使用自定义的loadURL,来避免这个问题。loadURL的实现来自关于UIWebView和PhoneGap的总结一文。

使用JavaScriptCore

iOS7之后,app新添加了一个JavaScriptCore/JavaScriptCore.h这个库用来做JS交互。
下面是h5的代码:

<!DOCTYPE html>
<html>
    <head lang="en">
        <meta charset="UTF-8">
            <title></title>
    </head>
    <body>
        <p></p>
        <div>
            <button onclick="showToast();">弹框提示</button>
            <button onclick="JSObjective.showAlert('参数1','参数2');">alert提示</button>
        </div>
        <p></p>
        <script>
            function showToast() {
                // 调用OC中的showToastWithparams方法
                showToastWithparams("参数1","参数2","参数3");
            }
            </script>
    </body>
</html>

在HTML中,添加一个事件有两种方法,一种是<button onclick="showToast();">弹框提示</button>,另一种是<button onclick="JSObjective.showAlert('参数1','参数2');">alert提示</button>;对于第一种写法,对应的OC代码如下:

- (void)webViewDidFinishLoad:(UIWebView *)webView{
    JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    context[@"showToastWithparams"] = ^() {
        //NSLog(@"当前线程 - %@",[NSThread currentThread]);
        NSArray *params = [JSContext currentArguments];
        for (JSValue *Param in params) {
            NSLog(@"%@", Param); // 打印结果就是JS传递过来的参数
        }
        //注意,这时候是在子线程中的,要更新UI的话要回到主线程中
        dispatch_async(dispatch_get_main_queue(), ^{
            UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"成功" message:[NSString stringWithFormat:@"js调用oc原生代码成功!"] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
            [alert show];
        });
    };    
}

对于第二种写法,首先要定义一个继承自JSExport的协议,协议里面定义的方法即是供JS调用的OC原生方法

@protocol TestJSExport<JSExport>
JSExportAs
(showAlert,
 - (void)showAlertWithParameters:(NSString *)parameterone parametertwo:(NSString *)parametertwo
 );
@end
- (void)webViewDidFinishLoad:(UIWebView *)webView{
    JSContext *context = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
    // 用TestJSExport协议来关联关联JCObjective的方法
    context[@"JSObjective"] = self;
}
#pragma mark -- TestJSExport协议

- (void)showAlertWithParameters:(NSString *)parameterone parametertwo:(NSString *)parametertwo {
    NSLog(@"当前线程 - %@",[NSThread currentThread]);// 子线程
    //NSLog(@"JS和OC交互 - %@ -- %@",parameterone,parametertwo);
   //注意,这个代理方法也是在子线程中的
    dispatch_async(dispatch_get_main_queue(), ^{
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:@"成功" message:[NSString stringWithFormat:@"js调用oc原生代码成功! - JS参数:%@,%@",parameterone,parametertwo] delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil, nil];
        [alert show];
    });
}

相关文章

网友评论

      本文标题:UIWebView和JS交互

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