2

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?

Community
  • 1
  • 1
user1019042
  • 2,428
  • 9
  • 43
  • 85

2 Answers2

1

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

Scriptable
  • 19,402
  • 5
  • 56
  • 72
  • It is a function of WKWebView but it requires a completion handler which I forgot about, see the documentation for it [here](https://developer.apple.com/library/ios/documentation/WebKit/Reference/WKWebView_Ref/#//apple_ref/occ/instm/WKWebView/evaluateJavaScript:completionHandler:). My code was in swift – Scriptable May 28 '16 at 12:28
0

For a complete answer, you want to: 1. inherit from WKNavigationDelegate 2. in viewDidLoad:

self.webView.navigationDelegate = self

3. and calling it in the didFinishNavigation, see this

Community
  • 1
  • 1
user1019042
  • 2,428
  • 9
  • 43
  • 85