UIWebView和WKWebView和原生的交互操作
全栈老韩
全栈工程师,擅长iOS App开发、前端(vue、react、nuxt、小程序&Taro)开发、Flutter、React Native、后端(midwayjs、golang、express、koa)开发、docker容器、seo优化等。
这里以UIWebview为主的演示,当然当今在iOS中依然废弃了UIWebview,普遍使用的是WKWebview。因为是我很早之前的笔记,所以仅供记录。
OC和JS的交互方式:
1. oc调用js:
(1)通过拦截URL的方式,js在web端src或者href时,通过截取sheme/ URL/ Path/ NavigationType等来决定是否执行某一个事件
UIWebView在shouldStart的代理方法中拦截;
WKWebView在decidePolicyForNavigation中进行拦截;
(2)
UIWebView:
NSString *jsStr = [NSString stringWithFormat:@"showAlert('%@')",@"这里是JS中alert弹出的message"];
[_webView stringByEvaluatingJavaScriptFromString:jsStr];
注意:该方法会同步返回一个字符串,因此是一个同步方法,可能会阻塞UI。
WKWebView:
WKWebView的evaluateJavaScript:completionHandler:
(3)
使用JavaScriptCore库来做JS交互。
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
NSString *textJS = @"showAlert('这里是JS中alert弹出的message')";
[context evaluateScript:textJS];
2. JS调用OC
(1)首先导入JavaScriptCore库, 然后在OC中获取JS的上下文
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
再然后定义好JS需要调用的方法,例如JS要调用share方法,则可以在UIWebView加载url完成后,在其代理方法中添加要调用的share方法:
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//定义好JS要调用的方法, share就是调用的share方法名
context[@"share"] = ^() {
NSLog(@"+++++++Begin Log+++++++");
NSArray *args = [JSContext currentArguments];
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"方式二" message:@"这是OC原生的弹出窗" delegate:self cancelButtonTitle:@"收到" otherButtonTitles:nil];
[alertView show];
});
for (JSValue *jsVal in args) {
NSLog(@"%@", jsVal.toString);
}
NSLog(@"-------End Log-------");
};
}
html中的演示(部分代码):
html
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
function secondClick() {
share('分享的标题','分享的内容','图片地址');
}
</script>
</head>
</html>
发布于2024-01-31 01:19:42
浏览量56·
暂无评论,快来发表第一条评论吧