从iOS7开始 苹果公布了JavaScriptCore.framework,使得JS与OC的交互更加方便.
首先导入JavaScriptCore.framework框架.
点击 Linked Frameworks and Libraries 的添加后 选择 JavaScriptCore.framework,选中JavaScriptCore.framework后 点击右下角Add 添加完成,创建一个UIWebView 用来测试.
/***************************************************测试代码如下****************************************************************/
#import"ViewController.h"
#import
@interfaceViewController()
@property(nonatomic,weak)UIWebView*myWebView;
@end
@implementationViewController
- (void)viewDidLoad {
[superviewDidLoad];
//初始化webView
UIWebView*mywebView = [[UIWebViewalloc]initWithFrame:CGRectMake(0,0, [UIScreenmainScreen].bounds.size.width, [UIScreenmainScreen].bounds.size.height)];
//添加webView到当前的viewController的view上
[self.viewaddSubview:mywebView];
self.myWebView= mywebView;
mywebView.delegate=self;
//网址
NSString*httpStr =@"http://www.baidu.com";
NSURL*httpUrl = [NSURLURLWithString:httpStr];
NSURLRequest*httpRequest = [NSURLRequestrequestWithURL:httpUrl];
[mywebViewloadRequest:httpRequest];
}
#pragma mark - UIWebView的代理方法
- (void)webViewDidFinishLoad:(UIWebView*)webView{
//网页加载完成时调用
// MARK: - OC调用JS
//首先创建JSContext对象(此处通过当前webView的键获取到就是从jscontext)
JSContext*context = [webViewvalueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
//准备执行的js代码
NSString*alertJS =@"alert('Warning')";
//通过OC方法调用js的alert
[contextevaluateScript:alertJS];
}
/********************************************************运行效果如下**********************************************************/