How to include a external library in JavaScriptCore?

眉间皱痕 提交于 2019-12-19 04:01:19

问题


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>

But with the syntax of this:

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.


回答1:


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];


来源:https://stackoverflow.com/questions/23397658/how-to-include-a-external-library-in-javascriptcore

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!