plgelso
plgelso

Reputation: 107

Get HTML element value using WKWebKit and Swift 3

Trying to get an html element name or value using preferred evaluate Javascript swift function using a WKWebView. I keep recieving nil. I think maybe my function is firing before the page is loaded, thus never finding the element. Right now just trying to get the element text by class name. Here is my code below in the ViewController

    import UIKit
    import WebKit

    class ViewController: UIViewController, WKUIDelegate, WKNavigationDelegate {

        var web: WKWebView!

    override func loadView() {
        let webConfiguration = WKWebViewConfiguration()
        web = WKWebView(frame: .zero, configuration: webConfiguration)
        web.uiDelegate = self
        view = web
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string: "http://www.appcoda.com")
        let myRequest = URLRequest(url: url!)
        web.load(myRequest)

        web.evaluateJavaScript("document.getElementByClassName('excerpt').innerText") {(result, error) in
            if error != nil {
                    print(String(describing:result))
            }
        }
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
}

Upvotes: 2

Views: 8365

Answers (1)

Code Different
Code Different

Reputation: 93151

You are partially right. The website won't finish loading by the time you call evaluateJavascript. But there are also other errors:

  • You should set the navigationDelegate instead of uiDelegate
  • Due to App Transport Security, URL requests to http addresses are disallowed. Use https if the website supports it or configure your app appropriately.
  • You misspelled the function name (missing the the s after getElement)
  • getElementsByClassName returns an array so you have to pick what element you want to find the innerText of

Try this:

override func viewDidLoad() {
    super.viewDidLoad()

    web = WKWebView(frame: .zero)
    web.navigationDelegate = self

    let url = URL(string: "https://www.appcoda.com")
    let myRequest = URLRequest(url: url!)
    web.load(myRequest)
}

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    web.evaluateJavaScript("document.getElementsByClassName('excerpt')[0].innerText") {(result, error) in
        guard error == nil {
            print(error!)
            return
        }

        print(String(describing: result))
    }
}

Upvotes: 1

Related Questions