javascript - 每次 iframe 重新导航时执行操作。 (javascript)

标签 javascript jquery iframe

我正在为某事制作一个机器人,该机器人旨在移动到文件的下一个“页面”并搜索字符串,并重复此操作直到找到该字符串。就搜索字符串而言,一切正常,但是它只导航到下一页一次(因此它只转到 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 个加载处理程序,其中一个位于您的函数内部,再次调用 runco​​de()。

您只需要 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/

相关文章:

javascript - 使用 JQuery 选择名称中包含多个点的输入标签

javascript - jQuery 简单的自动完成实现

asp.net - 加载前跳出框架页面

javascript - 自动将所有文件下载到计算机上用户首选的位置

javascript - 如何从字符串构建 JSON 对象键

javascript - 尝试在 Protractor 中使用类时获取 "TypeError: Dropdown is not a function"

jquery ui slider : call function on mouseup outside

java - 如何使用 Jquery、AJAX 和 Servlet 获得实时搜索功能?

jquery - Fancybox 在 IE 中加载 iframe 时卡住

android - 在 Android webview 中通过 iframe 加载 Youtube 视频