//js.html文件
<input type="button" value="testClick" onclick="testClick({'params.key' : 'params.value'})"/>
<input type="button" value="testShowMessage" onclick="testShowMsg()"/>
// ViewController.m
// 31-webview调用OC
#import "ViewController.h"
#import <JavaScriptCore/JavaScriptCore.h>
@interface ViewController () <UIWebViewDelegate>
@property (weak, nonatomic) IBOutlet UIWebView *wv;
@property (nonatomic, strong) JSContext *jsContext;
@end
@implementation ViewController
- (void)viewDidLoad {
[super viewDidLoad];
//创建URL
NSURL *url = [[NSBundle mainBundle] URLForResource:@"js.html" withExtension: nil];
//创建请求
NSURLRequest *request = [NSURLRequest requestWithURL: url];
//发送加载网页请求
[self.wv loadRequest: request];
}
- (void)webViewDidFinishLoad:(UIWebView *)webView
{
if (!self.jsContext) {
self.jsContext = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
// 关联打印异常
self.jsContext.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) {
context.exception = exceptionValue;
NSLog(@"异常信息:%@", exceptionValue);
};
//一个block函数给js调用 注意调用此函数是在webView线程
self.jsContext[@"testClick"] = ^(NSDictionary *param) {
NSLog(@"js调用oc testClick函数 成功.参数是:\n%@", param);
};
//注意调用时并不在主线程
self.jsContext[@"testShowMsg"] = ^() {
NSLog(@"js调用oc testShowMsg函数 成功");
UIAlertView *alertV = [[UIAlertView alloc] initWithTitle:@"提示" message:@"调用成功" delegate:nil cancelButtonTitle:@"确定" otherButtonTitles:nil];
[alertV show];
};
//这句可以不写 好像是返回一些浏览器的信息
id userAgent = [webView stringByEvaluatingJavaScriptFromString:@"navigator.userAgent"];
NSLog(@"userAgent类型:%@ \n值: %@", [userAgent class],userAgent);
}
}
@end
UIWebView 执行js代码
//得到整个网页源码
NSString *htmlSource = @"document.getElementsByTagName('html')[0].innerHTML;";
NSString *retHtmlSource = [self.wv stringByEvaluatingJavaScriptFromString:htmlSource];
//ById
NSString *js = @"document.getElementById('scd_num').innerHTML;";
NSString *retStr = [self.wv stringByEvaluatingJavaScriptFromString:js];
//ByClassName
NSString *js = @"document.getElementsByClassName('results')[0].innerHTML;";
NSString *retStr = [self.wv stringByEvaluatingJavaScriptFromString:js];
// 直接调用js函数
[self.wv stringByEvaluatingJavaScriptFromString:@"函数名('参数1, 参数2');"];
参考资料:
http://blog.csdn.net/woaifen3344/article/details/42742893