pragma mark -这里要事先注入 和 h5 约定的方法名称
WKWebViewConfiguration *config = [[WKWebViewConfiguration alloc] init];
NSArray *methodArr = @[@"startMiniProgram",@"getDataList",@"click"];//这里要事先注入 和 h5 约定的方法名称
[methodArr enumerateObjectsUsingBlock:^(NSString *methodStr, NSUInteger idx, BOOL * _Nonnull stop) {
[configuration.userContentController addScriptMessageHandler:self name:methodStr];
}];
WKPreferences *preferences = [WKPreferences new];
preferences.javaScriptCanOpenWindowsAutomatically = YES;
configuration.preferences = preferences;
webView要添加一句代码的监听
[webView.configuration.userContentController addScriptMessageHandler:self name:[iSecWebViewBridge iSecWebviewHttpJSMethodString]];
之后在这个方法里写监听到按钮点击
- (void)userContentController:(nonnull WKUserContentController *)userContentController didReceiveScriptMessage:(nonnull WKScriptMessage *)message {
NSLog(@"%@:%@",message.name,message.body);
//通过判断message.name 来判断是点击了那个按钮,做一些处理
//message.body 是H5传过来的参数
if ([message.name contains:@"startMiniProgram"]) {
} else if ([message.name contains:@"getDataList"]){
}
}
H5调用原生,H5给原生传值
H5写法,这里h5 跟原生代码之间传递参数要用字符串
<div class="mui-card-header mui-card-media" style="height:32vw;background-image:url(image/hd-3.jpeg)" onclick="getDataByType(data)"></div>
<div class="mui-card-header mui-card-media" style="height:32vw;background-image:url(image/hd-3.jpeg)" onclick="startMiniProgram(paraStr1,paraStr2)"></div>
function startMiniProgram(obje, fun) {
if (/(iPhone|iPad|iPod|iOS)/i.test(window.navigator.userAgent)) {
window.webkit.messageHandlers.startMiniProgram.postMessage(obj, fun);
} else {
window.Android.startMiniProgram(obj, fun);
}
}
function getDataByType(data) {
if (/(iPhone|iPad|iPod|iOS)/i.test(window.navigator.userAgent)) {
window.webkit.messageHandlers.getDataByType.postMessage(data);
} else {
window.Android.getDataByType(data);
}
}
OC代码调用H5,给原生传值,同样也只能传字符串,如果传json类型参数要传成字符串
//section js方法名 ticketNo 参数
NSString *str = [NSString stringWithFormat:@"%@(%@)",section,ticketNo];
[self.webView evaluateJavaScript:str completionHandler:^(id _Nullable complete, NSError * _Nullable error) {
if (complete) {
}
}];