JS与iOS原生方法交互的场景还是比较多的, 项目中用到原生加载h5界面, 然后js与原生交互.
- 原生端调用js端, 需要在h5界面的 '''<script ></script>''' 中实现方法
<!DOCTYPE html>
<html>
<head>
<title>OC与JS交互</title>
<meta charset="utf-8" />
<script>
function startAct() {
window.webkit.messageHandlers.Player.postMessage({
"start": true
});
}
function stopAct() {
window.webkit.messageHandlers.Player.postMessage({
"body": false
});
}
function callJSFunc(msg) {
alert(msg);
}
</script>
</head>
<body>
<input type="button" value="开始录音" onclick="startAct()" /> <br /><br />
<input type="button" value="停止录音" onclick="stopAct()" /><br />
</body>
</html>
在原生中调用js方法时使用:
NSString *js = @"callJSFunc()";
[self.wkWebView evaluateJavaScript:js completionHandler:^(id _Nullable result, NSError * _Nullable error) {
if (error) {
// NSLog(@"error == %@",error.description);
}else {
// NSLog(@"result == %@",result);
}
}];
- js端调用原生方法, 需要先添加 handler
WKUserContentController *userContentController = [[WKUserContentController alloc] init];
[userContentController addScriptMessageHandler:self name:@"Player"];
WKWebViewConfiguration *configuration = [[WKWebViewConfiguration alloc] init];
configuration.userContentController = userContentController;
wkWebView = [[WKWebView alloc] initWithFrame:self.view.frame configuration:configuration];
在js中调用原生方法时使用:
window.webkit.messageHandlers.<name>.postMessage(<messageBody>)
其中: <name>
为原生方法中定义的 name, 如Player
, <messageBody>
为传参
原生方法会在这个代理方法中获取到调用
- (void)userContentController:(WKUserContentController *)userContentController didReceiveScriptMessage:(WKScriptMessage *)message {
// message.name message.body 获取参数
}
网友评论