前端使用的是vue 直接起的本地項目蔫慧,也有本地html文件。
Demo地址:https://github.com/MYLILUYANG/WKWebViewDemo
創(chuàng)建WKWebView。設置相關內容剂癌。
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
// 注入方法 messageSend 在js中通過注入的方法向原生OC傳值怖现。
config.userContentController = [[WKUserContentController alloc] init];
[config.userContentController addScriptMessageHandler:self name:@"messageSend"];
// 偏好設置
config.preferences = [[WKPreferences alloc] init];
config.preferences.minimumFontSize = 0;
config.preferences.javaScriptEnabled = YES;
config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
_webView = [[WKWebView alloc] initWithFrame:CGRectMake(0, 0, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) configuration:config];
//如果使用本地html文件
// NSURL *path = [[NSBundle mainBundle] URLForResource:@"NativeJS" withExtension:@"html"];
[_webView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://localhost:8080"]]];
_webView.UIDelegate = self;
_webView.navigationDelegate = self;
[self.view addSubview:_webView];
// 監(jiān)聽_webview 的狀態(tài)
[_webView addObserver:self forKeyPath:@"loading" options:NSKeyValueObservingOptionNew context:nil];
[_webView addObserver:self forKeyPath:@"title" options:NSKeyValueObservingOptionNew context:nil];
[_webView addObserver:self forKeyPath:@"estimaedProgress" options:NSKeyValueObservingOptionNew context:nil];
創(chuàng)建完成后看一下html和js
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>OC與JS交互</title>
<style type="text/css">
* {
font-size: 40px;
}
</style>
</head>
<script>
function jsSendAlertToOC () {
alert('js調用原生警告面板');
}
function jsSendConfirmToOC() {
if(confirm('js 調用原生確認面板')){
document.getElementById('showMessage').innerHTML
= 'true';
} else {
document.getElementById('showMessage').innerHTML
= 'false';
}
}
function jsSendInputToOC(){
var response = prompt('請輸入您的測試數據');
document.getElementById('showMessage').innerHTML = response;
}
function jsSendMessageToOC(){
<!--通過 [config.userContentController addScriptMessageHandler:self name:@"messageSend"]; 注入"messageSend"來發(fā)出消息-->
window.webkit.messageHandlers.messageSend.postMessage({a:10, b:'c'})
}
</script>
<body>
<div>
<button onclick="jsSendAlertToOC()">js調用原生警告面板</button>
<br>
<br>
<button onclick="jsSendConfirmToOC()">js調用原生確認</button>
<br>
<br>
<button onclick="jsSendInputToOC()">js調用輸入框</button>
<br>
<br>
<button onclick="jsSendMessageToOC()">js發(fā)送數據給原生</button>
<br>
<br>
<div id="showMessage"></div>
</div>
</body>
</html>
界面就是這個樣子:
Simulator Screen Shot - iPhone 8 Plus - 2018-04-18 at 15.07.30.png
下邊就是原生處理從js發(fā)過來的消息:
1蕴茴、警告 2琉预、確認 3 董饰、輸入框 4、其他信息
1
#pragma mark - WKUIDelegate
//通過js alert 顯示一個警告面板圆米,調用原生會走此方法尖阔。
- (void)webView:(WKWebView *)webView runJavaScriptAlertPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(void))completionHandler
{
NSLog(@"顯示一個JavaScript警告面板, message = %@",message);
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];
}
2
//通過 js confirm 顯示一個確認面板,調用原生會走此方法榨咐。
- (void)webView:(WKWebView *)webView runJavaScriptConfirmPanelWithMessage:(NSString *)message initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(BOOL result))completionHandler
{
NSLog(@"運行JavaScript確認面板, message = %@", message);
UIAlertController *action = [UIAlertController alertControllerWithTitle:@"溫馨提示" message:message preferredStyle:UIAlertControllerStyleAlert];
[action addAction:[UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
completionHandler(NO);
}] ];
[action addAction:[UIAlertAction actionWithTitle:@"確認" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler(YES);
}]];
[self presentViewController:action animated:YES completion:nil];
}
3
//顯示輸入框
- (void)webView:(WKWebView *)webView runJavaScriptTextInputPanelWithPrompt:(NSString *)prompt defaultText:(nullable NSString *)defaultText initiatedByFrame:(WKFrameInfo *)frame completionHandler:(void (^)(NSString * _Nullable result))completionHandler
{
NSLog(@"顯示一個JavaScript文本輸入面板, message = %@",prompt);
UIAlertController *controller = [UIAlertController alertControllerWithTitle:defaultText message:prompt preferredStyle:UIAlertControllerStyleAlert];
[controller addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) {
textField.textColor = [UIColor redColor];
}];
[controller addAction:[UIAlertAction actionWithTitle:@"輸入信息" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
completionHandler([[controller.textFields lastObject] text]);
}]];
[self presentViewController:controller animated:YES completion:nil];
}
4
#pragma mark - WKScriptMessageHandler
//當js 通過 注入的方法 @“messageSend” 時會調用代理回調谴供。 原生收到的所有信息都通過此方法接收块茁。
-(void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message
{
NSLog(@"原生收到了js發(fā)送過來的消息 message.body = %@",message.body);
if ([message.name isEqualToString:@"messageSend"]) {
pushViewController *congtoller = [[pushViewController alloc] init];
[self.navigationController pushViewController:congtoller animated:YES];
}
}
通過原生主動調用js:
在原生界面中添加一個button主動調用js事件。
// 原生主動調用js方法
UIButton *button = [[UIButton alloc] initWithFrame:CGRectMake(0, 64, [UIScreen mainScreen].bounds.size.width, 40)];
[button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
[button setTitle:@"原生button調用js的 jsSendConfirmToOC 方法" forState:UIControlStateNormal];
[button addTarget:self action:@selector(btnAction) forControlEvents:UIControlEventTouchUpInside];
button.layer.cornerRadius = 20;
button.layer.masksToBounds = YES;
button.backgroundColor =[UIColor lightGrayColor];
[self.view addSubview:button];
響應button事件,通過點擊button 可以主動調用js中的方法桂肌。
-(void)btnAction{
NSString *js = @"jsSendConfirmToOC()";
// NSString *js = @"jsSendAlertToOC()";
// NSString *js = @"jsSendInputToOC()";
// NSString *js = @"jsSendMessageToOC()";
[self.webView evaluateJavaScript:js completionHandler:^(id _Nullable resp, NSError * _Nullable error) {
NSLog(@"error = %@ , response = %@",error, resp);
}];
}
上邊監(jiān)聽_webView狀態(tài)做出相應的處理(progress 就是隨手加的一個進度條):
-(void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context
{
if ([keyPath isEqualToString:@"loading"]) {
NSLog(@"loading");
}else if ([keyPath isEqualToString:@"title"]){
self.title = self.webView.title;
}else if ([keyPath isEqualToString:@"estimaedProgress"]){
self.progressView.progress = self.webView.estimatedProgress;
}
}
遇到的問題在主動調用js方法時
NSString *js = @"test2(\'OC 調用 js\')";
[self.webView evaluateJavaScript:js completionHandler:^(id _Nullable resp, NSError * _Nullable error) {
NSLog(@"error = %@ , response = %@",error, resp);
}];
方法時總是報錯
Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={WKJavaScriptExceptionLineNumber=1, WKJavaScriptExceptionMessage=ReferenceError: Can't find variable: test2, WKJavaScriptExceptionColumnNumber=6, WKJavaScriptExceptionSourceURL=about:blank, NSLocalizedDescription=A JavaScript exception occurred}
經過排查是因為vue的方法藏得比較深需要:
mounted (){
window. test2 = this. test2;
}