WKWebViewConfiguration
注入WKScriptMessageHandler
,由前端下发数据,客户端根据相关的数据作出相应的操作,OC
代码如下:
- (WKWebView *)wkWebView {
if (!_wkWebView) {
// 进行配置控制器
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
// 实例化对象
configuration.userContentController = [WKUserContentController new];
// 调用JS方法
[configuration.userContentController addScriptMessageHandler:self name:@"NativeModel"];
// 进行偏好设置
WKPreferences *preferences = [WKPreferences new];
preferences.javaScriptCanOpenWindowsAutomatically = YES;
// preferences.minimumFontSize = 20.0;
configuration.preferences = preferences;
// 初始化WKWebView
_wkWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, kNavigationBarHeight, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) configuration:configuration];
_wkWebView.UIDelegate = self;
_wkWebView.navigationDelegate =self;
}
return _wkWebView;
}
[self.view addSubview:self.wkWebView];
[self.wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]]];
@interface ViewController ()<WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate>
//webView
@property (nonatomic, strong) WKWebView *wkWebView;
@end
- 实现
WKScriptMessageHandler
代理方法,并在该代理方法中根据相应的注入js
的名称,实现对应的逻辑
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:@"NativeModel"]) {
NSDictionary *jsData = message.body;
NSLog(@"%@", message.name);
//读取js function的字符串
// NSString *jsFunctionString = jsData[@"result"];
// //拼接调用该方法的js字符串(convertDictionaryToJson:方法将NSDictionary转成JSON格式的字符串)
// NSString *jsonString = [NSDictionary convertDictionaryToJson:@{@"test":@"123", @"data":@"666"}];
// NSString *jsCallBack = [NSString stringWithFormat:@"(%@)(%@);", jsFunctionString, jsonString];
// //执行回调
// [self.weWebView evaluateJavaScript:jsCallBack completionHandler:^(id _Nullable result, NSError * _Nullable error) {
// if (error) {
// NSLog(@"err is %@", error.domain);
// }
// }];
}
}
前端代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>html5page-oc</title>
<script>
function btn1Click() {
window.webkit.messageHandlers.NativeModel.postMessage({name: 'zhangyutang', age: 12});
alert("after call");
}
</script>
</head>
<body>
<input type="button" value="button c" onclick="btn1Click()">
</body>
</html>
使用WKWebView
向js
传值
OC
代码如下
- (WKWebView *)wkWebView {
if (!_wkWebView) {
// 进行配置控制器
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
// 实例化对象
configuration.userContentController = [WKUserContentController new];
// 调用JS方法
[configuration.userContentController addScriptMessageHandler:self name:@"NativeModel"];
// 进行偏好设置
WKPreferences *preferences = [WKPreferences new];
preferences.javaScriptCanOpenWindowsAutomatically = YES;
// preferences.minimumFontSize = 20.0;
configuration.preferences = preferences;
// 初始化WKWebView
_wkWebView = [[WKWebView alloc]initWithFrame:CGRectMake(0, kNavigationBarHeight, [UIScreen mainScreen].bounds.size.width, [UIScreen mainScreen].bounds.size.height) configuration:configuration];
_wkWebView.UIDelegate = self;
_wkWebView.navigationDelegate =self;
}
return _wkWebView;
}
[self.view addSubview:self.wkWebView];
[self.wkWebView loadRequest:[NSURLRequest requestWithURL:[NSURL URLWithString:@""]]];
@interface ViewController ()<WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate>
//webView
@property (nonatomic, strong) WKWebView *wkWebView;
@end
- 实现代理方法,在协议加载完
WebView
后,注入相应的js
,将需要上传的参数上传给前端
- (void)webView:(WKWebView *)webView didFinishNavigation:(WKNavigation *)navigation
{
NSMutableDictionary *dic = [NSMutableDictionary new];
dic[@"username"] = @"里斯";
dic[@"token"] = @"1198203";
dic[@"avatar"] = @"";
NSString *jsonStr = [self convertToJsonData:dic];
NSString * jsStr = [NSString stringWithFormat:@"sendKey('%@')",jsonStr];
[self.wkWebView evaluateJavaScript:jsStr completionHandler:^(id _Nullable result, NSError * _Nullable error) {
//此处可以打印error.
}];
}
-(NSString *)convertToJsonData:(NSDictionary *)dict
{
NSError *error;
NSData *jsonData = [NSJSONSerialization dataWithJSONObject:dict options:NSJSONWritingPrettyPrinted error:&error];
NSString *jsonString;
if (!jsonData) {
NSLog(@"%@",error);
}else{
jsonString = [[NSString alloc]initWithData:jsonData encoding:NSUTF8StringEncoding];
}
NSMutableString *mutStr = [NSMutableString stringWithString:jsonString];
NSRange range = {0,jsonString.length};
//去掉字符串中的空格
[mutStr replaceOccurrencesOfString:@" " withString:@"" options:NSLiteralSearch range:range];
NSRange range2 = {0,mutStr.length};
//去掉字符串中的换行符
[mutStr replaceOccurrencesOfString:@"\n" withString:@"" options:NSLiteralSearch range:range2];
return mutStr;
}
前端代码如下
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<div onclick="newway()">新方法</div>
<input type="text" id = "show1">
<input type="text" id = "show2">
<input type="text" id = "show3">
</body>
<script src="js/jquery-2.1.4.js"></script>
<script>
function newway(){
alert("newway")
// var val = '{"token":"1198203","username":"张三","avatar":""}'
// sendKey(val)
}
function sendKey(val){
alert("sendKey")
let iOSInfo = JSON.parse(val);
$("#show1").val(iOSInfo.username)
$("#show2").val(iOSInfo.token)
$("#show3").val(iOSInfo.avatar)
}
</script>
</html>
遇到的问题
- 上传参数到前端,注入js时出现
Error Domain=WKErrorDomain Code=4 "A JavaScript exception occurred" UserInfo={NSLocalizedDescription=A JavaScript exception occurred
错误,检查上传的JSON
是否正确,保证上传的JSON
是一个正确的JSON
即可
网友评论