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

标签 javascript swift webkit javascriptcore

我的 Xcode 项目中有以下 .html 数据: enter image description here

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

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

关于javascript - Swift:使用 Swift 和 JavaScriptCore 打印 WebView 的 Html 标题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37495543/

相关文章:

javascript - 用于从字符串中剥离 URL 的正则表达式

javascript - angularjs组件的执行顺序是怎样的?

ios - 在 swift 中分享单个 gif

ios - 从另外两个核心数据对象创建复合对象

css - Webkit 浏览器不呈现位置 : relative correctly

javascript - 在 Android webkit 上以编程方式设置代理

javascript - 如何使用基本运算符检查字符串的数学表达式?

javascript - PhantomJS/WebKit 中奇怪的 JavaScript 行为

ios - 官方 iOS 应用程序上的 OAuth2 是否必须使用 webview?

css - Webkit 关键帧在 Chrome 中不起作用