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

use*_*030 9 javascript ios swift wkwebview

我正在尝试加载一个公交网站,这样我就可以为一个停止时间刮掉停止时间.加载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
    }
}
Run Code Online (Sandbox Code Playgroud)

Her*_*rix 4

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

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 });
Run Code Online (Sandbox Code Playgroud)

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

contentController.add(self, name: "stopTimesLoaded")
Run Code Online (Sandbox Code Playgroud)

最后添加处理数据的代码

func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage)
Run Code Online (Sandbox Code Playgroud)