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?

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

1 Comment

It is a function of WKWebView but it requires a completion handler which I forgot about, see the documentation for it here. My code was in swift
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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.