如何在JavaScriptCore中包含外部库?

问题描述:

我正在尝试通过JavaScriptCore加载外部库

I am trying to load a external library via JavaScriptCore

具体来说,我想要这样的最终结果:

Specifically I want the end result of this:

<script src="fancyLibrary.js" type="text/javascript"></script>

但是使用以下语法:

JSContext *context = [[JSContext alloc] initWithVirtualMachine:[[JSVirtualMachine alloc] init]];
[context loadExternalJavascriptFileWithName:@"fancyLibrary.js"];

JSValue *fancyFunction = context[@"fancy"];

目前有可能吗?我认为我可以在应用程序捆绑包中包含外部库,然后从那里调用它.只需将库加载到上下文中即可.

Is this possible at the current time? I figure I can include the external library in the app bundle and call it from there. It's a matter of loading the library into the context.

您只需要使用评估API即可在上下文中加载脚本的内容.实际上,这与浏览器遇到脚本标签时的操作非常接近.

You just need to use the evaluation API to load the contents of the script in the context. This is actually pretty close to what a browser does when it encounters a script tag.

NSURL *scriptURL = [NSURL URLWithString:@"path/to/fancyLibrary.js"];
NSError *error = nil;
NSString *script = [NSString stringWithContentsOfURL:scriptURL encoding:NSUTF8StringEncoding error:&error];
[context evaluateScript:script];