WKWebView JavaScript click() Invocation Fails to Trigger Action

I’m developing an Xcode project where I use WKWebView to load a webpage and then run JavaScript to simulate a click on a link. While other JavaScript functions—such as extracting innerHTML or handling form inputs—work perfectly, the simulated click does not lead to navigation as expected.

I have experimented with several variations, including adding punctuation at the end of the command, altering the case in the function name, and even switching the search method from classes to tag names. Additionally, testing the same approach in a UIWebView did not resolve the problem.

Below is a sample code snippet demonstrating my current approach. Note that the URL has been generalized and the code has been modified:

let myWebView = WKWebView()

if let sampleURL = URL(string: "https://sampledomain.com") {
    myWebView.load(URLRequest(url: sampleURL))
}

// After the page loads, a button triggers this code
// Although other JavaScript interactions succeed, this command does not simulate a click on the first link
myWebView.evaluateJavaScript("document.getElementsByTagName('a')[0].click();") { result, error in
    if let err = error {
        print("Error invoking click: \(err)")
    } else {
        print("Click simulated successfully")
    }
}

Has anyone experienced a similar issue or have any suggestions on how to correctly trigger the link click action using WKWebView’s JavaScript execution?