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) {
}];