代码之家  ›  专栏  ›  技术社区  ›  RyanTCB

iOS Swift上的javascript需要等待通过XMLHttpRequest加载动态内容

  •  0
  • RyanTCB  · 技术社区  · 6 年前

    我试着从一个页面上获取所有扩展名为.pdf的url,使用WKScriptMessageHandler在用户单击加载这些URL的元素之前,pdf URL不会显示在页面中。

    这就是我用来“点击”所有元素的方法,它公开了pdf的url。

    var element = document.querySelectorAll('[onclick*="javascript:ExpCollGroup"]');
    
                    for (var node of element){
                         node.click();
                    }
    

     var nodes = document.querySelectorAll('a[href$=".pdf"]');
    
              for (var circular of nodes){
                   urls.push(circular.getAttributeNode('href').nodeValue);
                }
    
    
               if (urls.length > 0){
                  window.webkit.messageHandlers.didFetchURLsFromServer.postMessage(urls);
    
    
                }
    

    nodes数组为空,因此其余的代码不会真正运行。

    webView.evaluateJavaScript("""
    
            if (document.readyState === 'complete') {
    
               var urls = [];
               var element = document.querySelectorAll('[onclick*="javascript:ExpCollGroup"]');
    
                for (var node of element){
                     node.click();
                }
    
    //The code below runs before the loop has loaded its content
    //Preventing the nodes array from being populated.
    //The only thing that seems to work is setting setTimeout function. 
    //I guess I need a call back when node.click() runs its last action of the loop
    
               var nodes = document.querySelectorAll('a[href$=".pdf"]');
    
              for (var circular of nodes){
                   urls.push(circular.getAttributeNode('href').nodeValue);
                }
    
    
               if (urls.length > 0){
                  window.webkit.messageHandlers.didFetchURLsFromServer.postMessage(urls);
                  }
    
    
        }
    
                        """, completionHandler: nil)
    

    如果文档没有考虑到新出现的带有所需URL的锚定标记,则会出现这种情况。当我在safari桌面上运行相同的脚本时,它可以工作,但在iOS上url数组的长度保持为0。

    我尝试过使用Promise,但在iOS上没有被解雇,但在桌面safari上工作。 非常感谢。

    0 回复  |  直到 6 年前