Swift: 使用 Swift 和 JavaScriptCore 打印 Html WebView 的标题

Swift: Print Html title of WebView using Swift And JavaScriptCore

我的 Xcode 项目中有这个 .html 数据:

我正在尝试使用这两行来读取标题值:

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

但它只打印:

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

不要将 UIWebView 用于针对 iOS 8 及更高版本的新代码,而是使用 WKWebView。 Apple 在 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.

下面是如何用 WKWebView 计算 Javascript:

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