iOS开发-WKWebView与JS的交互

作者丨iOS_xuanhe
https://www.jianshu.com/p/10ee497d905f
iOS8以后,Apple公司推出了WKWebView,对比之前的UIWebView不论是处理速度还是内存性能,都有了大幅度的提升!
那么下面我就分享一下WKWebView与JS的交互.
首先使用WKWebView.你需要导入WebKit #import
然后初始化一个WKWebView,设置代理,并且执行代理的方法.在网页加载成功的时候,我们会调用一些JS代码对网页进行设置.
WKWebView的代理一共有三个:
WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler
.WKWebView调用JS方法
/**
iOS调用js里的navButtonAction方法并传入两个参数
@param 'Xuanhe' 传入的参数
@param 25 传入的参数
@return completionHandler 回调
*/
[self.webView evaluateJavaScript:@"navButtonAction('Xuanhe',18)" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
NSLog(@"response:%@,error:%@",response,error);
}];
网页加载完成
//网页加载完成
-(void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation{
//设置JS
NSString *js = @"document.getElementsByTagName('h1')[0].innerText";
//执行JS
[webView evaluateJavaScript:js completionHandler:^(id _Nullable response, NSError * _Nullable error) {
NSLog(@"value: %@ error: %@", response, error);
}];
}
通过以上操作就成功获取到h1标签的文本内容了.如果报错,可以通过error进行相应的错误处理.
2.加载JS代码
创建WKWebView,并在创建时向JS写入内容.
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
WKWebView *webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, kNavBarH, kScreenW, kScreenH-kNavBarH) configuration:config];
webView.navigationDelegate = self;
webView.UIDelegate = self;
//获取HTML上下文的第一个h2标签,并写入内容
NSString *js = @"document.getElementsByTagName('h2')[0].innerText = '这是一个iOS写入的方法'";
WKUserScript*script = [[WKUserScript alloc] initWithSource:js injectionTime:WKUserScriptInjectionTimeAtDocumentEnd forMainFrameOnly:YES];
[config.userContentController addUserScript:script];
[self.view addSubview:webView];
调用JS方法:
[[webView configuration].userContentController addScriptMessageHandler:self name:@"show"];
遵循代理WKScriptMessageHandler后,调用JS的方法show;
实现WKScriptMessageHandler代理方法,调用JS方法后的回调,可以获取到方法名,以及传递的数据:
//js传递过来的数据
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
NSLog(@"%@",message.name);//方法名
NSLog(@"%@",message.body);//传递的数据
}
获取JS弹窗信息
遵循WKUIDelegate代理,实现相关代理方法:
// alert
//此方法作为js的alert方法接口的实现,默认弹出窗口应该只有提示信息及一个确认按钮,当然可以添加更多按钮以及其他内容,但是并不会起到什么作用
//点击确认按钮的相应事件需要执行completionHandler,这样js才能继续执行
////参数 message为 js 方法 alert() 中的
-(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() 中的
-(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(, );中的
//参数defaultText 为 prompt(, );中的
-(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];
}
demo地址
https://github.com/zxhkit/WKWebViewAndJS
推荐↓↓↓

长
按
关
注
?【16个技术公众号】都在这里!
涵盖:程序员大咖、源码共读、程序员共读、数据结构与算法、黑客技术和网络安全、大数据科技、编程前端、Java、Python、Web编程开发、Android、iOS开发、Linux、数据库研发、幽默程序员等。

关注公众号:拾黑(shiheibook)了解更多
[广告]赞助链接:
四季很好,只要有你,文娱排行榜:https://www.yaopaiming.com/
让资讯触达的更精准有趣:https://www.0xu.cn/

随时掌握互联网精彩
- 1 助力全国统一大市场建设 7904612
- 2 比大熊猫更濒危的动物全国仅剩1只 7808765
- 3 伊朗一港口发生高强度爆炸 7712560
- 4 五一大量外国人涌入中国 7616747
- 5 中使馆回应“特朗普称中国须让步” 7519926
- 6 谢霆锋儿子现身演唱会 7427006
- 7 女子网购避孕套被骑手骚扰 7328174
- 8 中方为何站出来反制?王毅回答 7232204
- 9 多地宣布发钱奖励结婚 7138558
- 10 韩国一公司要求员工每天至少洗澡1次 7046020