1

Having trouble using JSContext to pass a variable to a javascript function. The error says stringToSend is undefined:

func sendSomething(stringToSend : String) {
        appController?.evaluateInJavaScriptContext({ (context) -> Void in
            context.evaluateScript("myJSFunction(stringToSend)")
            }, completion: { (evaluated) -> Void in
                print("we have completed: \(evaluated)")
        })
    }

2 Answers 2

4

Here is how I like to communicate from Swift to Javascript:

func sendSomething(stringToSend : String) {
    appController?.evaluateInJavaScriptContext({ (context) -> Void in

       //Get a reference to the "myJSFunction" method that you've implemented in JavaScript
       let myJSFunction = evaluation.objectForKeyedSubscript("myJSFunction")

       //Call your JavaScript method with an array of arguments
       myJSFunction.callWithArguments([stringToSend])

       }, completion: { (evaluated) -> Void in
          print("we have completed: \(evaluated)")
    })
}

Make sure myJSFunction is implemented in your javascript context when you call this method.

Your stringToSend String will automatically be mapped to a javascript string when using callWithArguments.

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

1 Comment

How would you do it if you want to send more complex Objects? I tried JSExport but it didnt work
2

The string needed Swift's String Interpolation, plus extra quotes, like this:

func sendSomething(stringToSend : String) {
        appController?.evaluateInJavaScriptContext({ (context) -> Void in
            context.evaluateScript("myJSFunction('\(stringToSend)')")
            }, completion: { (evaluated) -> Void in
                print("we have completed: \(evaluated)")
        })
    }

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.