Search code examples
javascriptiosswiftwebkitwkwebview

Get text from input text field in WKWebView


I am working with WKWebView and loaded url in the same web-view which is having login page (email and password input text).

email input text field like this:

<input class="input" type="email" placeholder="" data-automation-id="email" name="email" maxlength="256" value="">

Can someone guide me that how to get the value this input text?

 webView.evaluateJavaScript("document.getElementById('email').value", completionHandler: { (jsonRaw: Any?, error: Error?) in
            guard let jsonString = jsonRaw as? String else { return }
            print(js)
        })

Tried this but not working :(

TIA


Solution

  • If you don't want to add id to the element, use getElementsByClassName instead which returns an array and pick the first element to read the value of the email field:

    Example:


    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
        webView.evaluateJavaScript("document.getElementsByClassName('input')[0].value") {(result, error) in
            guard error == nil else {
                print(error!)
                return
            }
            
            print(String(describing: result))
        }
    }
    

    Sample HTML string used for testing:

    <html>
      <body>
          <input class="input" type="email" placeholder="" data-automation-id="email" name="email" maxlength="256" value="5556454">
      </body>
    </html>