在WKWebView中加载网站后,如何检测元素何时可见?

时间:2018-07-27 03:24:21

标签: javascript ios swift wkwebview

我正在尝试加载大众运输网站,以便我可以抓取特定停靠站的停靠时间。加载网址后,停止时间会稍后通过javascript动态加载。我的目标是使用“停止时间”类来检测元素的存在。如果html中存在这些元素,则可以解析html。但是在解析html之前,我必须等待“ stop-time”类的这些元素出现。我通读了其他一些SO问题,但我无法将其拼凑在一起。我正在实现didReceive消息函数,但我不确定如何在javascript中加载我需要检测元素(“ stop-time”类的元素)的存在的方法。我成功注入了一些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
    }
}

1 个答案:

答案 0 :(得分:1)

首先,您需要注入下一个脚本以通过变异观察器检测元素的出现:

var observer = new MutationObserver(function(mutations) {
    mutations.forEach(function(mutation) {
      console.log('mutation.type = ' + mutation.type);
      for (var i = 0; i < mutation.addedNodes.length; i++) {
        var node = mutation.addedNodes[i];
        if (node.nodeType == Node.ELEMENT_NODE && node.className == 'stop-time') {
            var content = node.textContent;
            console.log('  "' + content + '" added');
            window.webkit.messageHandlers.stopTimesLoaded.postMessage({ data: content });
        }
      }
    });
  });
observer.observe(document, { childList: true, subtree: true });

然后,您需要订阅事件“ stopTimesLoaded”:

contentController.add(self, name: "stopTimesLoaded")

最后添加代码以处理其中的数据

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)