Search code examples
javascriptwkwebview

wkwebview evaluate javascript click on nav bar title


https://enquiry.indianrail.gov.in/mntes/. I have tried various ways to click on the "Live Station Info" in the nav bar buttons. I am new to javascript. Is this the right way to click on the button?

enter image description here

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
   webView.evaluateJavaScript("document.getElementsByClassName('nav-link')[1].click();

Solution

  • It's OK. Only it's not robust enough, since the index of the item might change in the future. It would be better to add a unique ID or another custom attribute, so that you can identify the item safely. Or you can directly call the onMenuItem method, instead of clicking the item, as follows.

    Also, you will need to prevent the code from executing again and again, since webView:didFinish: will be called again after you click the item, since the page will be reloaded.

    var liveStationClicked = false
    
    func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!) {
    
        if !liveStationClicked {
            liveStationClicked = true
            webView.evaluateJavaScript("if (onMainMenu) onMainMenu('liveStation','');");
        }
    }