最近项目中需要用到js与原生app交互, 点击h5中的按钮, 并把h5中的参数传递到原生页面.
1. 首先在app端遵守协议<WKScriptMessageHandler,WKNavigationDelegate,WKUIDelegate>
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
// 设置偏好设置
config.preferences = [[WKPreferences alloc] init];
config.preferences.minimumFontSize = 10;
config.preferences.javaScriptEnabled = YES;
config.preferences.javaScriptCanOpenWindowsAutomatically = NO;
config.processPool = [[WKProcessPool alloc] init];
// 通过JS与webview内容交互
config.userContentController = [[WKUserContentController alloc] init];
// 注入JS对象名称AppModel,当JS通过AppModel来调用时,
// 我们可以在WKScriptMessageHandler代理中接收到
[config.userContentController addScriptMessageHandler:self name:@"AppModel"];
//通过默认的构造器来创建对象
self.webView = [[WKWebView alloc] initWithFrame:self.view.bounds
configuration:config];
NSURL *path = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"html"];
[self.webView loadRequest:[NSURLRequest requestWithURL:path]];
[self.view addSubview:self.webView];
WKScriptMessageHandler代理回调
- (void)userContentController:(WKUserContentController *)userContentController
didReceiveScriptMessage:(WKScriptMessage *)message {
if ([message.name isEqualToString:@"AppModel"]) {
// 打印所传过来的参数,只支持NSNumber, NSString, NSDate, NSArray,
NSLog(@"%@", message.body);
}
}
3. 在js中注入AppModel
function buttonClick() {
// AppModel是我们所注入的对象
window.webkit.messageHandlers.AppModel.postMessage({body: '我是传递的参数'});
}
=========== 分割线 ============
OC向js中传值
native调用js
OC端
// OC端
- (void)btnClick:(UIButton *)sender {
[self.wkWebView evaluateJavaScript:@"jsFunc('张飞')" completionHandler:^(id _Nullable response, NSError * _Nullable error) {
//TODO
NSLog(@"%@ %@",response,error);
}];
}
js端写
function jsFunc(name) {
// 打印name参数
// 点击OC中的按钮, js端该方法即可响应
//TODO
}