Search code examples
swifturlwebtap

SWIFT 2.0 - Is it possible to simulate a click or a user tap in a view?


I Want to code a fake user click on a web view button to automatically load the right web page. I am working in Swift 2.0, the url doesn't contain any index page.

I want to click on the NOTES button, the url of the page is here:

https://legymnase67.la-vie-scolaire.fr/vsn.main/;jsessionid=E2D99A46028465A9D7F636521C64088B.node2?autolog=70caa4a471e8f6f0856735aed506b01a6307246c445beb160259f75c1c700f7978631d698cc5e0e890452bd182e5960e6153be7c4a3d2615ff0daf981a17877d46e472cdf2ef2328977c3957a58121e3556c4b9b808e22a76d0cbb994292a2144d64f367714c7dfbf4d3e24cea5f0274


Solution

  • You can simulate the button click using javascript, since the button is a browser element on the webview.

    To run javascript through swift, use the evaluateJavaScript method. Using evaluateJavaScript() you can run any JavaScript in a WKWebView and read the result in Swift. This can be any JavaScript you want, which effectively means you can dig right into a page and pull out any kind of information you want.

    webView.evaluateJavaScript("document.getElementById('theButtonElement').click()") { (result, error) in
        if error != nil {
            print(result)
        }
    }