1

I'm loading html page inside of WKWebView and I need to click on a link. For example. loading apple.com

override func viewDidAppear() {
    super.viewDidAppear()
    webView.load(urlString: "https://www.apple.com")
}

and locating the links to click:

func webView(_ webView: WKWebView, didFinish navigation: WKNavigation!){
    webView.evaluateJavaScript("document.getElementsByClassName('cta-links')[0].innerHTML") { (result, error) in
        if error != nil {
            print(error?.localizedDescription ?? "")
        }
        if result != nil{
            print("code with links \(result)")
        }
    }

}

The output I'll get is:

<a href="/us/shop/goto/buy_iphone/iphone_xr" class="cta more" aria-label="Buy now with trade in" data-analytics-title="buy now with trade-in" data-analytics-region="buy">Buy<span class="visuallyhidden">with trade in</span></a>

<a href="/us/shop/goto/trade_in" class="cta more" aria-label="Learn more about trade in" data-analytics-title="Learn more about trade-in" data-analytics-region="learn more">Learn more</a>

But my question to you guys is how can I click on of those links for example on this link:

<a href="/us/shop/goto/trade_in" class="cta more" aria-label="Learn more about trade in" data-analytics-title="Learn more about trade-in" data-analytics-region="learn more">Learn more</a>

There is a way to click on that link either with javascript or any other way in swift?

I'll really appreciate your help.

1 Answer 1

1

To click the following link, you need to identify it in some way, for sake of example I will use the label, as the class is not unique, ideally you would have an ID.

<a href="/us/shop/goto/trade_in" class="cta more" aria-label="Learn more about trade in" data-analytics-title="Learn more about trade-in" data-analytics-region="learn more">Learn more</a>

In your script you will then need to find this element, you can use querySelectorAll() do to this.

let elementToClick = document.querySelectorAll('[aria-label="Learn more about trade in"]')[0];

And then in your script, call the DOM click() method

elementToClick.click();

This will emulate a click and redirect you to the path given in the href.

Sign up to request clarification or add additional context in comments.

8 Comments

what you mean with "myCheck"?
This is simply the ID i gave your href, I am then grabbing that element by ID in the javascript and then using the .click() method on it
the problem is the urls doesn't have an ID per code sniped I post. They have a class
you will need a unique identifier of some sort, otherwise you will trigger a click on all of the links with the class name you specify
Can you post an example?
|

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.