Search code examples
javascriptswiftwebkitjavascriptcore

Swift: Print Html title of WebView using Swift And JavaScriptCore


I have this .html data in my Xcode project: enter image description here

I'm trying to read the title value using both of these lines:

document.title 
document.getElementsByTagName(\"title\")[0].innerHTML; 

but it only prints:

result is: undefined

import UIKit
import JavaScriptCore
class ViewController: UIViewController {

override func viewDidLoad() {
    super.viewDidLoad()

    // Do any additional setup after loading the view, typically from a nib.
    let myWebView:UIWebView = UIWebView(frame: CGRectMake(0, 0, UIScreen.mainScreen().bounds.width, UIScreen.mainScreen().bounds.height))
    let localfilePath = NSBundle.mainBundle().URLForResource("home", withExtension: "html");
    let myRequest = NSURLRequest(URL: localfilePath!);
    myWebView.loadRequest(myRequest);

    //let jsSource = "var testFunct = function(message) { return document.title;}"
    let jsSource = "var testFunct = function(message) { return document.getElementsByTagName(\"title\")[0].innerHTML;}"

    let context = JSContext()
    context.evaluateScript(jsSource)
    let testFunction = context.objectForKeyedSubscript("testFunct")
    let result = testFunction.callWithArguments(["the message"])
    print("result is: \(result)")

    self.view.addSubview(myWebView)
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

Solution

  • Don't use UIWebView for new code targeting iOS 8 and above, use WKWebView instead. Apple has this to say on UIWebView Documentation:

    In apps that run in iOS 8 and later, use the WKWebView class instead of using UIWebView. Additionally, consider setting the WKPreferences property javaScriptEnabled to NO if you render files that are not supposed to run JavaScript.

    And here's how you can evaluate Javascript with WKWebView:

    self.webView.evaluateJavaScript("document.title") { result, error in
        print(result!)
    }