1

The following code is how to call Javascript functions from Swift

        if let jsSourcePath = Bundle.main.path(forResource: "jssrc", ofType: "js"){
        do {
            let jsSourceContents = try String(contentsOfFile: jsSourcePath)
            self.jsContext.evaluateScript(jsSourceContents)
        }
        catch {
            print(error.localizedDescription)
        }

I thought I could do something similar for jquery. I have an identical codeblock to the one above, the only difference is I specify the official jquery library to evaluate.

I get the following error when I try to evaluate jquery.js, however.

TypeError: undefined is not an object (evaluating 'document.createElement')

Why is document.createElement resolving to undefined? Do I need to modify the class jsContext is a member of, such that the view is a WKWebView?

1 Answer 1

3

Document refers to document object model or DOM. Since your Swift view is not a web page there is no DOM so this is why its undefined. I think you can call Javascript functions from Swift but once the Javascript function relies on the DOM and manipulating HTML in the DOM I think this is where you will have issues in Swift.

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

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.