HTML演示代码
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<script type="application/javascript">
function openURL(string) {location.href = string;}
</script>
</head>
<body>
<h1>用户登录</h1>
<button onclick="openURL('hj://call?phoneno=520')">打电话</button>
</body>
</html>
在OC中执行JS脚本
stringByEvaluatingJavaScriptFromString:
该方法执行JS脚本代码,并返回执行结果
一般通过上面这个方法,传递参数给JS中的某个函数并执行,就达到了在OC中执行JS脚本的目的
1. 单行语句
NSString * value = [webView stringByEvaluatingJavaScriptFromString:@"document.body.innerHTML"];
2. 多条语句一
NSString * line1 = @"var h1 = document.getElementsByTagName('h1')[0];";
NSString * line2 = @"h1.parentNode.removeChild(h1);";
[webView stringByEvaluatingJavaScriptFromString:line1];
[webView stringByEvaluatingJavaScriptFromString:line2];
3. 多条语句二
NSMutableString * JSString = [NSMutableString string];
[JSString appendFormat:@""];
[webView stringByEvaluatingJavaScriptFromString:JSString];
JS调用OC
JS调用OC,可在JS中创建触发事件,然后在该事件中发出一个网页链接跳转的请求,然后该网络请求被
UIWebViewDelegate的webView:shouldStartLoadWithRequest:navigationType:方法拦截到。
形如 hj://call?phoneno=1314
hj是自定义的网络协议,用以区分http/https/rtmp/ftp...等协议
call就是要响应的某种事件
phoneno=1314就是需要携带的参数
那么该协议的意思就是说,JS想打电话,号码是1314
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType {
if ([request.URL.scheme isEqualToString:@"hj"]) {
if ([request.URL.host isEqualToString:@"call"]) {
[self callActionWithURL:request.URL.query];
}
return NO;
}
return YES;
}
- (void)callActionWithURL:(NSString *)url {
NSLog(@"要拨打电话的路径:%@", url);
}