WKWebView:获取所选链接的标题

时间:2015-11-21 08:36:42

标签: ios swift wkwebview

在加载到WKWebView的网站上选择链接标题的最简单方法是什么?

示例:当用户点击链接时

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

我想获取<a>元素的内容(在这种情况下为Go to foo)。

直接通过WKNavigationDelegate获取链接网址,但我无法找到直接公开标题的内容。我设法通过将Javascript注入Web视图来获得标题,但这感觉有点笨拙(见下文)。

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)
    }

}

有没有更好的方法呢?

0 个答案:

没有答案