Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Getting title from WKWebView using evaluateJavaScript

I have a very simple/easy question but have absolutely zero experience with java. I have a WKWebView and I want to get the title text of the page using the javascript document.getElementById.

The webpage I am trying to get the title from has this code:

<html>
<body>
<div class="toolbar">
<h1 id="pageTitle">Schedules</h1>
</div>
</body>
<html>

This code is abridged so I apologize for any errors.

Then I am trying to access the pageTitle in Swift with:

func webView(webView: WKWebView, didFinishNavigation navigation: WKNavigation!) {

    webView.evaluateJavaScript("document.getElementById('pageTitle').value") { (result, error) -> Void in
        if error != nil {
            print(result)
        }
    }
}

And the result is returning nil. After hours of searching I still have no idea how to get this to work. Any help is appreciated.

like image 961
Tamarisk Avatar asked Sep 24 '15 00:09

Tamarisk


1 Answers

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.

like image 153
SilkyPantsDan Avatar answered Oct 12 '22 15:10

SilkyPantsDan