Getting title from WKWebView using evaluateJavaScript
In your code when there is some error, then the code will print the result. This'll print nothing when there is no error occuer.
So change you code to this, everything works well.
func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {
webView.evaluateJavaScript("document.getElementById('pageTitle').innerHTML") { (result, error) -> Void in
if error != nil {
print(error)
}
print(result)
}
}
As mentioned by @SilkyPantsDan, if you are just interested in the title
, there's no need to use JS. Firstly you start observing:
override func viewDidLoad() {
super.viewDidLoad()
webView.addObserver(self, forKeyPath: #keyPath(WKWebView.title), options: .new, context: nil)
}
And handle your logic when title
is updated:
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
if keyPath == "title" {
title = webView.title
}
}
Finally you should stop observing if you are supporting iOS 8.0, as observers are not removed automatically before iOS 9.0:
deinit {
webView.removeObserver(self, forKeyPath: "title")
//webView.removeObserver(self, forKeyPath: "estimatedProgress")
}
You shouldn't need to use javascript to retrieve the page title. WKWebView has a title
property that will retrieve this for you
https://developer.apple.com/library/ios/documentation/WebKit/Reference/WKWebView_Ref/#//apple_ref/occ/instp/WKWebView/title
title
The page title. (read-only)SWIFT
var title: String? { get }
The WKWebView class is key-value observing (KVO) compliant for this property.
Available in iOS 8.0 and later.