skip to Main Content

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

2

Answers


  1. The input tag doesn’t have an id of email which is why the lookup by id is failing. Update the web page so the input tag has an id set to email.

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

    With the id="email" added, the document.getElementById('email').value should find the input and give you the value.

    Login or Signup to reply.
  2. 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>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search