我正在尝试使用这两行读取标题值:
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/