美文网首页iOS开发webview&jsiOS 进阶
WKWebView的js交互(附demo)

WKWebView的js交互(附demo)

作者: 夜凉听风雨 | 来源:发表于2018-07-24 10:37 被阅读1088次

前言

之前有写过一篇是UIWebView的js交互,但是UIWebView是有内存泄露问题的。所以现在大家一般都会使用WKWebView。
现在总结一下WKWebView加载网页还有与JS交互的方法。

加载网页分为加载本地html文件和加载线上的网页链接。为了方便讲解,我这里用的是加载本地html文件的方式。

把一个html文件导入到工程中

图片.png

导入webView框架

#import <WebKit/WebKit.h>

遵循代理

<WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler>

初始化webView 设置代理

    WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
    WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 64, self.view.frame.size.width, self.view.frame.size.height - 64) configuration:config];
    webView.navigationDelegate = self;
    webView.UIDelegate = self;

向网页注入js

注入js分为在网页document加载完毕注入和加载之前注入
// 在加载之前注入,这时注入的js会在网页的所有元素加载之前和网页本身的js执行之前执行
WKUserScriptInjectionTimeAtDocumentStart
// 在加载之后注入,当网页的元素加载之后以及网页本身的js执行之后才会执行注入的js。
WKUserScriptInjectionTimeAtDocumentEnd

    NSString *js = @"document.getElementsByTagName('h2')[0].innerText = '我是ios为h5注入的方法'";
    WKUserScript *script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
    [config.userContentController addUserScript:script];

加载本地html文件

    NSString *filePath = [[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"];
    NSString *htmlString = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:nil];
    NSURL *url = [[NSURL alloc] initWithString:filePath];
    [self.webView loadHTMLString:htmlString baseURL:url];

WKNavigationDelegate代理方法实现

// 开始加载
- (void)webView:(WKWebView *)webView didStartProvisionalNavigation:(WKNavigation *)navigation {
    // 可以在这里做正在加载的提示动画 然后在加载完成代理方法里移除动画
}

// 网络错误
- (void)webView:(WKWebView *)webView didFailProvisionalNavigation:(null_unspecified WKNavigation *)navigation withError:(NSError *)error {
    // 在这里可以做错误提示
}
    

// 网页加载完成
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation {
     // 在这里可以移除正在加载的提示动画
}

WKUIDelegate代理方法实现

由于安全机制的问题,WKWebView默认对JavaScript下alert类的方法(包括alert(),confirm(),prompt())做了拦截,如果要想正常使用,需要实现WKWebView的三个代理方法

// alert
//此方法作为js的alert方法接口的实现,默认弹出窗口应该只有提示信息及一个确认按钮,当然可以添加更多按钮以及其他内容,但是并不会起到什么作用
//点击确认按钮的相应事件需要执行completionHandler,这样js才能继续执行
////参数 message为  js 方法 alert(<message>) 中的<message>
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler();
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}

// confirm
//作为js中confirm接口的实现,需要有提示信息以及两个相应事件, 确认及取消,并且在completionHandler中回传相应结果,确认返回YES, 取消返回NO
//参数 message为  js 方法 confirm(<message>) 中的<message>
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"提示" message:message?:@"" preferredStyle:UIAlertControllerStyleAlert];
    [alertController addAction:([UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(NO);
    }])];
    
    [alertController addAction:([UIAlertAction actionWithTitle:@"确认" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(YES);
    }])];
    
    [self presentViewController:alertController animated:YES completion:nil];
}

// prompt
//作为js中prompt接口的实现,默认需要有一个输入框一个按钮,点击确认按钮回传输入值
//当然可以添加多个按钮以及多个输入框,不过completionHandler只有一个参数,如果有多个输入框,需要将多个输入框中的值通过某种方式拼接成一个字符串回传,js接收到之后再做处理
//参数 prompt 为 prompt(<message>, <defaultValue>);中的<message>
//参数defaultText 为 prompt(<message>, <defaultValue>);中的 <defaultValue>
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable))completionHandler{
    
    UIAlertController *alertController = [UIAlertController alertControllerWithTitle:prompt message:@"" preferredStyle:UIAlertControllerStyleAlert]; [alertController addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
        textField.text = defaultText;
    }];
    
    [alertController addAction:([UIAlertAction actionWithTitle:@"完成" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        completionHandler(alertController.textFields[0].text?:@"");
    }])];
    [self presentViewController:alertController animated:YES completion:nil];
}

iOS调用js

下面的代码是调用了js里的navButtonAction方法,并且传入了两个参数,回调里面response是这个方法return回来的数据。

    [self.webView evaluateJavaScript:@"navButtonAction('Jonas',25)" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
        NSLog(@"%@=====%@",response,error);
    }];

js调iOS

当JS端想传一些数据给iOS.那它们会调用下方方法来发送。

window.webkit.messageHandlers.<方法名>.postMessage(<数据>)

注意:上方代码在JS端写会报错,导致网页后面业务不执行.可使用try-catch执行。

在web端具体代码如下:

           try{
                window.webkit.messageHandlers.show.postMessage("我是js传递过来的数据");
            }catch (e){
                
            }

在OC中的处理方法如下。它是WKScriptMessageHandler的代理方法name和上方JS中的方法名相对应。

- (void)addScriptMessageHandler:(id <WKScriptMessageHandler>)scriptMessageHandler name:(NSString *)name;

具体代码如下:

[[webView configuration].userContentController addScriptMessageHandler:self name:@"show"];

收到js传来的消息时会走WKScriptMessageHandler协议方法

- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    NSLog(@"%@",message.name);// 方法名
    NSLog(@"%@",message.body);// 传递的数据
}

demo下载

最后为大家提供了一个简单的demo,能够更清晰的看到如何使用。
下载地址:
https://github.com/jiangbin1993/WKWebView-

相关文章

网友评论

    本文标题:WKWebView的js交互(附demo)

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