Search code examples
htmlswiftmacossafariwebkit

How to get text from Web page in macOS via Swift?


How to get a string of text like this:

Simple Text Example...

from macOS' Safari page via Swift 4?

@IBOutlet weak var label: NSTextField!
@IBOutlet weak var webView: WKWebView!

override func viewDidLoad() {
    super.viewDidLoad()
    let string = "http://127.0.0.1:8080/101"
    let url = NSURL(string: string)
    let request = URLRequest(url: url! as URL)
    self.webView.load(request as URLRequest)

    //this doesn't work
    label.stringValue = webView.webFrame.frameElement.innerText
}

Here is HTML structure:

<html>
  <head></head>
    <body>
      Simple Text Example...
    </body>
</html>

UPDATE:

I've tried the following method but it has Void return...

webView.evaluateJavaScript("document.body.innerText") { (result, error) in
    if error != nil {
        print(result)
    }
}

Solution

  • for iOS, in the webview's delegate method

    func webViewDidFinishLoad(_ webView: UIWebView) {  
        var string = webView.stringByEvaluatingJavaScript(from: "document.body.textContent")
        print(string)
    }
    

    for macOS, in the webview's navigation delegate:

    override func viewDidLoad() {
        webview.nagivationDelegate = self
        ...
    }
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.evaluateJavaScript("document.body.textContent") { (string, error) in
                print(string)
        }
    }