oc:
#import "JSOCViewController.h"
@interface JSOCViewController ()<UIWebViewDelegate>
@end
@implementation JSOCViewController
- (void)viewDidLoad {
[super viewDidLoad];
// Do any additional setup after loading the view.
self.title = @"JS调用OC";
UIWebView *webView = [[UIWebView alloc]initWithFrame:CGRectMake(0, 40, self.view.frame.size.width, self.view.frame.size.height-40)];
webView.delegate = self;
NSString *path = [[NSBundle mainBundle]pathForResource:@"index" ofType:@"html"];
NSURL *url = [NSURL fileURLWithPath:path];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView loadRequest:request];
[self.view addSubview:webView];
}
- (BOOL)webView:(UIWebView *)webView shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)navigationType{
NSString *urlstr = request.URL.absoluteString;
NSRange range = [urlstr rangeOfString:@"ios://zw"];
if (range.length!=0) {
[self show];
}
return YES;
}
-(void)show{
NSLog(@"JS调用OC");
}
html:
<!DOCTYPE html>
<html lang="zh-CN">
<head>
<meta charset="utf-8">
<title>OC与JS互相调用</title>
</head>
<body>
<input type="button" value="JS调用OC方法" onclick="js_call_oc()"/>
<script type="text/javascript">
function js_call_oc()
{
var iFrame;
iFrame = document.createElement("iframe");
iFrame.setAttribute("src", "ios://zw");
iFrame.setAttribute("style", "display:none;");
iFrame.setAttribute("height", "0px");
iFrame.setAttribute("width", "0px");
iFrame.setAttribute("frameborder", "0");
document.body.appendChild(iFrame);
// 发起请求后这个iFrame就没用了,把它从dom上移除掉
iFrame.parentNode.removeChild(iFrame);
iFrame = null;
}
</script>
</body>
</html>