'Detect button click in WKWebview

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?



Solution 1:[1]

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
        } 
     }

Solution 2:[2]

The workaround I did for listening to button event click is to modify the html button by adding a href.

For example:

Adding a href to your button event "window.location.href = “iosapp://button1”;"

In your ios app

    -(void)webView:(WKWebView *)webView decidePolicyForNavigationAction:(WKNavigationAction *)navigationAction decisionHandler:(void (^)(WKNavigationActionPolicy))decisionHandler
{

    if([navigationAction.request.URL.absoluteString isEqualToString:@"iosapp://button1"])
    {
        //Do whatever you need when this button is clicked
    }
    
    decisionHandler(WKNavigationActionPolicyAllow);
}

Solution 3:[3]

Vey simple solution:

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

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Maulik Pandya
Solution 2 jjlei
Solution 3 ewebbers