Search code examples
javascriptiosswift3xcode8wkwebview

clicking on a button with no link in webview swift


I had written a code to auto login a website that I usually login everyday.

the j3 command is not working and it doesn't click on the button and doesn't navigate to the next page but the rest of the code is working very well. The j3 code's javascript command is correct because I had written it first in a python code and it worked perfectly well but I have this issue in swift webview that doesn't login.

class ViewController: UIViewController , WKNavigationDelegate {
    @IBOutlet weak var user: UITextField!
    @IBOutlet weak var pass: UITextField!
    @IBOutlet var webView: WKWebView!

    override func viewDidLoad() {
        super.viewDidLoad()

        let url = URL(string: "https://karsanj.net/login.php")!
        webView.navigationDelegate = self
        webView.load(URLRequest(url : url))
    }

    @IBAction func onLogInTapped(){
        let j1="document.getElementById('username').value='\(user.text!)';"
        let j2="document.getElementById('password').value='\(pass.text!)';"
        let j3="document.getElementsByClassName('btn').click();"
        webView.evaluateJavaScript(j1, completionHandler: nil)
        webView.evaluateJavaScript(j2, completionHandler: nil)
        webView.evaluateJavaScript(j3, completionHandler: nil)
    }

}


Solution

  • document.getElementsByClassName always returns an array containing all the elements with such a ClassName, even if there is only one element with the specified class name, like I guess this is your case.

    So I recommand, instead of this:

        let j3="document.getElementsByClassName('btn').click();"
    

    You should write this :

        let j3="document.getElementsByClassName('btn')[0].click();"