【发布时间】:2019-01-04 03:04:25
【问题描述】:
我正在尝试加载一个公交网站,以便获取给定站点的停靠时间。在我加载 url 后,稍后会通过 javascript 动态加载停止时间。我的目标是检测具有“停止时间”类的元素的存在。如果这些元素存在于 html 中,我可以解析 html。但在我可以解析 html 之前,我必须等待这些具有“停止时间”类的元素出现。我通读了一堆其他 SO 问题,但我无法将它们拼凑起来。我正在实现 didReceive 消息函数,但我不确定如何加载我需要检测元素(具有“停止时间”类的元素)的存在的 javascript。我成功注入了一些 javascript 以防止显示位置权限弹出窗口。
override func viewDidLoad() {
super.viewDidLoad()
let contentController = WKUserContentController()
let scriptSource = "navigator.geolocation.getCurrentPosition = function(success, error, options) {}; navigator.geolocation.watchPosition = function(success, error, options) {}; navigator.geolocation.clearWatch = function(id) {};"
let script = WKUserScript(source: scriptSource, injectionTime: .atDocumentStart, forMainFrameOnly: true)
contentController.addUserScript(script)
let config = WKWebViewConfiguration()
config.userContentController = contentController
webView = WKWebView(frame: .zero, configuration: config)
self.view = self.webView!
loadStopTimes("https://www.website.com/stop/1000")
}
func loadStopTimes(_ busUrl: String) {
let urlString = busUrl
let url = URL(string: urlString)!
let urlRequest = URLRequest(url: url)
webView?.load(urlRequest)
}
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if(message.name == "stopTimesLoaded") {
// stop times now present so take the html and parse the stop times
}
}
【问题讨论】:
-
如果“stop-time”元素加载了脚本,您可以在加载完成后从您的 javascript 调用应用程序中的方法。 stackoverflow.com/questions/9826792/…
标签: javascript ios swift wkwebview