1

Here is the code I am using to try and get the length of an item in a websites html to a variable in swift so I can run a function depending on the length of the Class

self.viewController?.webBrowser?.evaluateJavaScript("document.getElementsByClassName('siteName').length") { (value, error) in
    print("LENGTH IS ", value)
    print("ERROR IS ", error)
    let jsValue = value as? Int

    if jsValue == 0{
        self.waitClick()
    }else{
        self.startItemColor()
    }
}

No matter what the length is, I will get 0 as the value

2 Answers 2

1

Probably the DOM Element was not ready yet when you tried to access it. You should move your code to didFinish method of WKNavigationDelegate protocol.

So your UIViewController should look like this:

class ViewController: UIViewController, WKNavigationDelegate {

    override func viewDidLoad(){
      super.viewDidLoad()

      ...
      webBrowser.navigationDelegate = self
      webBrowser.load(request)
      ...
    }

    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.evaluateJavaScript("document.getElementsByClassName('siteName').length") { (value, error) in
            print("LENGTH IS ", value)
            print("ERROR IS ", error)
            let jsValue = value as? Int

            if jsValue == 0{
                self.waitClick()
            } else {
                self.startItemColor()
            }
        }
    }

}

Also don't forget to enable App Transport Security in your info.plist like this

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

In case this doesn't work try to debug why. Probably try to call a method in your JavaScript that returns the length of class="sitename" element and also that console.log(length) so that you can go further in debugging and see what's going on.

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

Comments

0

Looks like getElementsByClassName returns an array, so if an element with that class name is not found, then the array will have length of zero. It isn't getting the length of the element itself.

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.