1

How would I go about changing the value of a Swift variable based on a JavaScript variable? (Passing a JavaScript variable to Swift)

My goal is simply to conduct an if statement using a JavaScript variable, and than edit the swift variable based on that.

Example in code of what I am trying to do:

var checkElement = false
webView.evaluateJavaScript("var element = document.getElementById(\"element\");"){ (value, error) in
        if let err = error {
            print(err)
        }
}
if (element != null){
checkElement = true
}

I understand this won't work due to element only existing in JavaScript. Although, how would I pass the element variable to Swift?

2 Answers 2

4

I thought I would answer this myself.

First, ensure your class is conforming to the correct protocols: WKScriptMessageHandler is required and you may also need WKNavigationDelegate.

Before initializing your WKWebView add a userContentController to its configuration. This is what will act as a 'bridge' from your JavaScript to Swift.

var webView = WKWebView()
let configuration = WKWebViewConfiguration()
configuration.userContentController.add(self, name: "messageName")
webView = WKWebView(frame: .zero, configuration: configuration)

Now initialize the userContentController() function and handle the received content within it. Ex.

public func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
    print("Name: \(message.name)")
    print("Body: \(message.body as! String)")
}

Now within the JavaScript inside your evaluateJavaScript() add the following line to push whatever data to Swift:

window.webkit.messageHandlers['messageName'].postMessage('Message Body!');

Now, when that JavaScript line is called Swift will output the following:

Name: messageName
Body: Message Body!
Sign up to request clarification or add additional context in comments.

Comments

0

You can get variable in Swift code by interception clicked URL via UIWebViewDelegate method webView:shouldStartLoadWithRequest:navigationType:

Simulate click you can via iframe in JS.

Here is an example in Objective-C, but it will be same on Swift - http://iwearshorts.com/blog/how-to-call-uiwebview-from-javascript/

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.