前端使用的是vue 直接起的本地项目,也有本地html文件。
Demo地址:https://github.com/MYLILUYANG/WKWebViewDemo
创建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];
// 监听_webview 的状态
[_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];
创建完成后看一下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"来发出消息-->
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发送数据给原生</button>
<br>
<br>
<div id="showMessage"></div>
</div>
</body>
</html>
界面就是这个样子:
下边就是原生处理从js发过来的消息:
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发送过来的消息 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);
}];
}
上边监听_webView状态做出相应的处理(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;
}