我正在尝试使用WKScriptMessageHandler从页面获取所有扩展名为.pdf的URL。直到用户单击加载这些URL的元素,该pdf URL才会暴露给页面。
这是我用来“单击”所有元素的方法,它公开了pdf URL。
var element = document.querySelectorAll('[onclick*="javascript:ExpCollGroup"]');
for (var node of element){
node.click();
}
我现在需要提取所有这些URL,以便脚本以
继续 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 Array的长度保持为0。
我曾尝试使用Promise,但并未在iOS上启动,但可在桌面浏览器中使用。 提示非常感谢。 注意:网页不是我的