Search code examples
javascriptswiftmacoswkwebviewjavascriptcore

Return JavaScript value in Swift


I need to return a value in Swift by executing JavaScript, but I am having trouble I have searched everywhere, but I can't find anything that works. To execute the JavaScript, I am using

webby.evaluateJavaScript("document.querySelector(\"pre\").innerText;")

(Webby is the name of the web view) The JavaScript returns a string, which I would like to access in Swift. How would I accomplish this? Thanks.


Solution

  • To access the value you have to provide a completion handler to evaluateJavaScript, see the docs:

    webby.evaluateJavaScript("<your code goes here>") { result, error in
      if let result = result {
        // your result handling goes here
      }
    }