WKWebView: get the name of the selected link

What is the easiest way to get the name of the link selected on a website uploaded to WKWebView?

Example: when a user removes a link

<a href="http://www.foo.com">Go to foo</a>

I want to get the contents of an element <a>( Go to fooin this case).

Directly get the URL of the link through WKNavigationDelegate, but I could not find anything that directly reveals the title. I managed to get the name by injecting Javascript into the web view, but this seems a bit awkward (see below).

import Foundation
import UIKit
import WebKit

class ViewController: UIViewController, WKNavigationDelegate {

    override func viewDidLoad() {
        let webView = WKWebView(frame: view.bounds)
        view.addSubview(webView)
        webView.loadRequest(NSURLRequest(URL: NSURL(string: "http://stackoverflow.com")!))
        webView.navigationDelegate = self
    }

    func webView(webView: WKWebView, decidePolicyForNavigationAction navigationAction: WKNavigationAction, decisionHandler: (WKNavigationActionPolicy) -> Void) {
        print("Link URL: \(navigationAction.request.URL)")

        let script = "function findLink() {" +
                       "var els = document.getElementsByTagName('a');" +
                       "for (var i = 0, l = els.length; i < l; i++) {" +
                         "var el = els[i];" +
                         "if (el.href === '\(navigationAction.request.URL!.absoluteString)') {" +
                           "return el.innerHTML;" +
                         "}" +
                       "}" +
                       "return null;" +
                     "}" +
                     "findLink();";
        webView.evaluateJavaScript(script) { (result, error) -> Void in
            if let result = result {
                print("Link Title: \(result)")
            }
        }

        decisionHandler(.Allow)
    }

}

Is there a better way to do this?

+4
source share

Source: https://habr.com/ru/post/1616842/


All Articles