3
votes

In my IOS Application I've created a WKWebview of a website that I'm not owning myself. So inside my:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {

I've a couple of .evaluateJavascript that add data to textfields, removes elements on the website etc.

But I'm trying to add an .evaluateJavascript (Or other) that will recognize a button click on the website.

I've tried to add this by doing this code:

bookingView.evaluateJavaScript("document.getElementById('optional_button').onclick();") { (key, err) in
        if let err = err{
            print(err.localizedDescription)
        }
        else{
            print("You tapped the button!")
        }

But that doesnt work. Everytime I open up the WebView the app prints out "You tapped the button" even if I didn't.

So, can I detect a button click with evaluateJavascript?

2
@user1374 I've tried that one.. Does not work :/ - Putte
@Putte have you got the answer? if so kindly share here - muthukumaresh
@muthukumaresh I don’t.. i’m sorry. Dosent have the project anymore - Putte

2 Answers

2
votes

you can catch the url and react to it

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        decisionHandler(.allow)
        guard let urlAsString = navigationAction.request.url?.absoluteString.lowercased() else {
            return
        }

        if urlAsString.range(of: "the url that the button redirects the webpage to") != nil {
        // do something
        } 
     }
0
votes

Vey simple solution:

webView.evaluateJavaScript("document.getElementsByTagName('input')[0].click()", completionHandler: nil)

where replace 0 with the button index in the web page.