Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to include a external library in 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>

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.

like image 550
Cezar Avatar asked Dec 09 '25 03:12

Cezar


1 Answers

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];
like image 185
Tayschrenn Avatar answered Dec 10 '25 17:12

Tayschrenn



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!