WKWebView 与 JS 相互调用

WKWebView 官方文档

WKWebView 是现代 WebKit API 在 iOS 8 和 OS X Yosemite 应用中的核心部分。它代替了 UIKit 中的 UIWebView 和 AppKit 中的 WebView,提供了统一的跨双平台 API。

号称拥有 60fps 滚动刷新率、内置手势、高效的 app 和 web 信息交换通道、和 Safari 相同的 JavaScript 引擎。

1、 WKWebView调用JS

//调用 JS 函数 NaturalKeyQuery()
     NSString *js = [NSString  stringWithFormat:@"NaturalKeyQuery('%@')", target];

    [webView evaluateJavaScript:js completionHandler:^(id _Nullable other, NSError * _Nullable error) {
        NSLog(@"call function NaturalKeyQuery: %@", error.userInfo);
    }];

这里有一个坑,调用JS函数需要传递参数时,需要用单引号 ” 将参数包起来。否则会报如下错误

WKJavaScriptExceptionMessage = "ReferenceError: Can't find variable

2、JS 调用 OC

这个方法可以注入LoadingState 的 MessageHandler到JS,JS通MessageName 回调OC 方法。当然也可以通过这个方法实现JS 主动与OC进行通讯。

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

-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
    if ([message.name isEqualToString:@"LoadingState"]) {
        NSLog(@"---recieve loading message: %@", message.body);
    } 
}

JS端可以通过如下代码回调JS:

window.webkit.messageHandlers.<对象名>.postMessage(<数据>)

3、WKWebView注入cookies

WKWebView可以通过注入WKUserScript 来实现注入cookies的功能。详细代码如下:

 // add accessToken as session_id, and sc_id
 NSString *cookie = [NSString  stringWithFormat:@"document.cookie = 'session_id=%@'; document.cookie = 'CLIENT=App'; document.cookie = 'sc_id=1'", _accessToken == nil ? @"": _accessToken];

WKUserScript *cookieScript = [[WKUserScript alloc]
                                  initWithSource:cookie                                   injectionTime:WKUserScriptInjectionTimeAtDocumentStart
                                  forMainFrameOnly:NO];

 [webView.configuration.userContentController addUserScript:cookieScript];

4、JS 调用 OC Alert

JS不能alert()函数直接调用OC UIAlertView,通过JS端实现了alert()函数后,会触发WKWebView WKUIDelegate 的相关函数,需要实现下面的代理方法才能展示原生的UIAlertView。

//在JS端调用alert函数时,会触发此代理方法。
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler;

//JS端调用confirm函数时,会触发此方法
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler;

//JS端调用prompt函数时,会触发此方法
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler;

5、WKWebView 清除浏览器缓存
可以通过WKWebView调用JS 清楚缓存的函数来实现清除 浏览器缓存功能。

NSString *js = @"function clearCache(){localStorage.setItem('fundType',null);localStorage.setItem('fundTypeIndex',null);}clearCache();";

    [self evaluateJavaScript:js completionHandler:^(id _Nullable other, NSError * _Nullable error) {

    }];

参考文档:
NShipster WKWebView 英文版本
NShipster WKWebView 中文版本

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值