我正在为某事制作一个机器人,该机器人旨在移动到文件的下一个“页面”并搜索字符串,并重复此操作直到找到该字符串。就搜索字符串而言,一切正常,但是它只导航到下一页一次(因此它只转到 online.php?page=2。我相信这是因为 iframe.contentWindow.load 仅触发一次,代码的第一次运行。因此,当它移动到新页面时,它不会继续。
有什么想法吗?
document.body.innerHTML = '' //Out with the old
var iframe = document.createElement('iframe');
var increm = 1
iframe.src = 'online.php?page=' + parseInt(increm)
iframe.style.height= '3000px'
iframe.style.width = '100%'
document.body.appendChild(iframe); //In with the new
$( iframe.contentWindow ).load(function() { //Once EVERYTHING has loaded
runcode()
});
function runcode(){
whole = iframe.contentWindow.document.body.innerText
var sub = "StringToSearchFor";
if(whole.indexOf(sub) > -1){ //If the string is found on the page
console.log('The string has been found on this page')
}else{ //Otherwise
increm = increm+1
iframe.src = 'online.php?page=' + parseInt(increm); //Move to the next page
$( iframe.contentWindow ).load(function() { //rinse
runcode() //repeat
});
}
}
最佳答案
您有 2 个加载处理程序,其中一个位于您的函数内部,再次调用 runcode()。
您只需要 1,但不要将其附加到发生更改的内容。内容删除意味着处理程序已删除。因此,请执行以下操作:
$( iframe ).load(function() { runcode() });
或者
$( iframe ).on("load", function() { runcode() });
或者
$( iframe ).on("load", ".newchilddiv", function() { runcode() });
编辑:innerText 也导致错误
whole = iframe.contentWindow.document.body.innerText
关于javascript - 每次 iframe 重新导航时执行操作。 (javascript),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35875018/