源码

iOS开发-WKWebView与JS的交互

iOS8以后,Apple公司退出了WKWebView,对比之前的UIWebView不论是处理速度还是内存性能,都有了大幅度的提升!

那么下面我就分享一下WKWebView与JS的交互.

首先使用WKWebView.你需要导入WebKit #import

然后初始化一个WKWebView,设置代理,并且执行代理的方法.在网页加载成功的时候,我们会调用一些JS代码对网页进行设置.

WKWebView的代理一共有三个:WKUIDelegate,WKNavigationDelegate,WKScriptMessageHandler

1.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地址

作者:iOS_xuanhe

链接:https://www.jianshu.com/p/10ee497d905f

(0)

本文由 投稿者 创作,文章地址:https://blog.isoyu.com/archives/ioskaifa-wkwebviewyujsdejiaohu.html
采用知识共享署名4.0 国际许可协议进行许可。除注明转载/出处外,均为本站原创或翻译,转载前请务必署名。最后编辑时间为:1 月 3, 2019 at 04:29 下午

热评文章

发表回复

[必填]

我是人?

提交后请等待三秒以免造成未提交成功和重复