Home>

When tapping a link in the site displayed in Swift WKWebView
Is there a way to get linked characters?

How to get linked characters instead of URL.

Please tell me.
Thank you.

Supplement
The source site is an arbitrary website, not your own.

  • Answer # 1

    A linked character is a thing surrounded by a tags, right?
    http://www.htmq.com/html/a.shtml

    Please refer to the following page.

    https://qiita.com/peta-m175/items/102d6d723fd87e722f83

    Callbacks when you want to receive JavaScript execution results
    WKUserContentController

    When callback occurs, receive using WKScriptMessageHandler.

    After that, you can write javascript to get the text enclosed in a tag.

  • Answer # 2

    If you have created your own site, I think that js can be used.
    If it is not (any website), I don't feel it as a simple method.
    As a possible method, I came up with a technique that fetches the HTML of the web and pulls the a tag text that matches the URL of the link.
    However, since it is not acquired from what was clicked, if there is the same link URL with different text, it can not be determined.

    webView.evaluateJavaScript ("document.body.innerHTML", completionHandler: {(html, error)->Void in
         print (html)
    })
    func webView (_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy)->Void) {
         if let url = navigationAction.request.url {
             // Find the part where url matches from html
         }
    }

    How to get HTML source read by WKWebView