JavaScriptCore(簡稱 JSCore)是蘋果在 iOS 中提供的 framework,讓 Objective-C 與 JavaScript 之間的互操作變得相當便利。它預設不會被加入專案,需要手動添加。
加入之後,可以發現 JavaScriptCore.h 主要包含以下五個檔案:
#import "JSContext.h" #import "JSValue.h" #import "JSManagedValue.h" #import "JSVirtualMachine.h" #import "JSExport.h"
各檔案職責如下:

以下透過實例來熟悉 JSCore 的用法。
案例一:JS 中定義了 add(a, b),需要在 OC 中呼叫它。
- (void)OCCallJS {
self.context = [[JSContext alloc] init];
NSString *js = @"function add(a,b) { return a + b }";
[self.context evaluateScript:js];
JSValue *addJS = self.context[@"add"];
JSValue *sum = [addJS callWithArguments:@[@(10), @(17)]];
NSInteger intSum = [sum toInt32];
NSLog(@"intSum: %zi", intSum);
}
有兩種途徑:block 與 JSExport protocol。以下先在 OC 中定義一個待呼叫的方法:
- (NSInteger)add:(NSInteger)a and:(NSInteger)b {
return a + b;
}
- (void)JSCallOC_block {
self.context = [[JSContext alloc] init];
__weak typeof(self) weakSelf = self;
self.context[@"add"] = ^NSInteger(NSInteger a, NSInteger b) {
return [weakSelf add:a and:b];
};
JSValue *sum = [self.context evaluateScript:@"add(4,5)"];
NSInteger intSum = [sum toInt32];
NSLog(@"intSum: %zi", intSum);
}
@protocol AddJSExport// 用巨集把 JS 端的方法名指定為 add JSExportAs(add, - (NSInteger)add:(NSInteger)a and:(NSInteger)b); @property (nonatomic, assign) NSInteger sum; @end
// AddJSExportObj.h @interface AddJSExportObj : NSObject@property (nonatomic, assign) NSInteger sum; @end // AddJSExportObj.m @implementation AddJSExportObj - (NSInteger)add:(NSInteger)a and:(NSInteger)b { return a + b; } @end
- (void)JSCallOC_JSExport {
self.context = [[JSContext alloc] init];
// 例外處理
self.context.exceptionHandler = ^(JSContext *context, JSValue *exception) {
[JSContext currentContext].exception = exception;
NSLog(@"exception: %@", exception);
};
self.addObj = [[AddJSExportObj alloc] init];
// JS 中的 OCAddObj 即對應 OC 中的 AddJSExportObj
self.context[@"OCAddObj"] = self.addObj;
[self.context evaluateScript:@"OCAddObj.sum = OCAddObj.add(2,30)"];
NSLog(@"%zi", self.addObj.sum);
}
案例三:本地預置一系列方法,由伺服器下發 JS 腳本決定要執行哪些,從而在遠端控制客戶端行為。
- (void)initJS {
__weak typeof(self) weakSelf = self;
self.context[@"execute1"] = ^{ [weakSelf execute1]; };
self.context[@"execute2"] = ^{ [weakSelf execute2]; };
}
- (void)execute1 { NSLog(@"execute1"); }
- (void)execute2 { NSLog(@"execute2"); }
- (NSString *)getJS {
// 可改為向伺服器索取
return @"execute2()";
}
- (void)executeByJs {
[self initJS];
NSString *js = [self getJS];
[self.context evaluateScript:js];
}
在 UIWebView 中,我們可以在 - (void)webViewDidFinishLoad:(UIWebView *)webView 裡透過 KVC 取得當前容器的 JSContext,之後便能方便地進行 hybrid 操作:
JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"];
案例演示:在 HTML 中呼叫 OC 實作的分享與相機功能。
function jsCallNative() {
WBBridge.callCamera();
}
function jsCallNative2() {
var shareInfo = "分享內容";
var str = WBBridge.share(shareInfo);
alert(str);
}
@protocol WebViewJSExport- (void)callCamera; - (NSString *)share:(NSString *)shareString; @end
@interface ViewController ()@property (nonatomic, strong) JSContext *context; @property (nonatomic, strong) UIWebView *webView; @end @implementation ViewController - (void)initWebView { _webView = [[UIWebView alloc] initWithFrame:self.view.bounds]; _webView.delegate = self; [self.view addSubview:_webView]; NSURL *url = [[NSURL alloc] initWithString:@"https://localhost:8080/myDiary/HelloWorld.html"]; [_webView loadRequest:[NSURLRequest requestWithURL:url]]; } - (void)webViewDidFinishLoad:(UIWebView *)webView { JSContext *context = [self.webView valueForKeyPath:@"documentView.webView.mainFrame.javaScriptContext"]; _context = context; // 把本物件橋接給 JS,JS 中的 WBBridge 即代表 self [_context setObject:self forKeyedSubscript:@"WBBridge"]; _context.exceptionHandler = ^(JSContext *context, JSValue *exceptionValue) { context.exception = exceptionValue; NSLog(@"異常資訊:%@", exceptionValue); }; } - (void)callCamera { NSLog(@"呼叫相機"); } - (NSString *)share:(NSString *)shareString { NSLog(@"分享::::%@", shareString); return @"分享成功"; } @end
如此一來,就能在 webView 中直接呼叫 native 組件,完成一個簡易的 hybrid 功能。這補充了 UIWebView 實現 hybrid 的另一種方式;還有一種常見做法是建立隱藏的 iframe 來攔截請求,可參考「iOS H5 容器的一些探究(一):UIWebView 和 WKWebView 的比較和選擇」。
至於 WKWebView,目前還沒有一勞永逸取得 JSContext 的官方途徑。
javascriptcore 官方文件
JavaScriptCore 使用
iOS 7 新 JavaScriptCore 框架入門介紹