user1019042 user1019042 - 6 months ago 49
Swift Question

Swift: How to use JavascriptCore to call a function in a loaded file

Similar to a regular js file that starts with referenced external query and then your js custom code, I need to do the same in Swift using JavascriptCore.

I saw this Objective-C example:

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


It does the first part of bringing down an external js file, but I want to also add a js block calling some of the functions in that referenced file. How do I do that!? Can you do it in Swift?

Answer

you can just call evaluateJavascript on the webView to call functions and get information, so you can do things like:

webView.evaluateJavascript("someFuncton();") { (result, error) in
    if (!error) {
         print(result(
    }
}

webView.evaluateJavascript("document.height") { (result, error) in
    if (!error) {
         print(result(
    }
}

You can even post messages from the Javascript back to native swift functions using webKit using message hanlders. see this ref

Here is an objective-c guide on sending messages both ways using Javascript