JavaScript调用oc函数,与uiwebview互动
项目》Build Phases》Link Binary With Libraries
添加JavaScriptCore.framework的引用
如图所示:
#import <JavaScriptCore/JavaScriptCore.h>
在uiwebview的加载完成事件中添加jscontext的定义
- (void)webViewDidFinishLoad:(UIWebView *)_webView
JSContext *context =[webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
context[@"tianyan"] = ^() {
NSLog(@"+++++++Begin Log+++++++");
NSArray *args = [JSContext currentArguments];
for (JSValue *jsVal in args) {
NSLog(@"%@", jsVal);
}
JSValue *this = [JSContext currentThis];
NSLog(@"this: %@",this);
NSLog(@"-------End Log-------");
};
//[context evaluateScript:@"log('ider', [7, 21], { hello:'world', js:100 });”];
JSContext *context2 = [webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
context2[@“login"] = ^(int n) {
NSLog(@“参数是:%d”,n);
};
网页内容:
<a href="javascript:tianyan();”> 点击调用</a>
<a href="javascript:login(123);">点击调用带参数</a>