【问题标题】:How to wait until element present in javascript?如何等到元素出现在javascript中?
【发布时间】:2020-04-25 13:18:57
【问题描述】:
(function() {
    document.evaluate('/html/body/nav/section[4]/div/form[1]/input[4]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue.click();
    Sleep(15);
    window.close();
})();

所以点击功能有效,但一旦我添加睡眠 windows.close 不再有效?我还在学习 Javascript,所以有人可以帮忙吗?我要做的就是让它点击投票按钮,然后关闭活动标签。

【问题讨论】:

  • javascript中没有Sleep,这就是你的脚本出错的原因。
  • 我尝试了一个 setTimeout(function, milliseconds) 但是我的脚本跳过了点击部分,只是关闭了选项卡而不执行点击功能。单击“投票”按钮后,我注意到网站 URL 更改为 ImageNumber?flash=Rated%20Image。如何检测 URL 更改然后执行 Window.close?

标签: javascript xpath sleep tampermonkey


【解决方案1】:

试试这个函数,它会在元素存在时等待。

function waitWhileElementPresent(cssLocator, timeoutInSeconds) {
    var currentTime = new Date().getTime();
    var endTime = currentTime + timeoutInSeconds * 1000;
    var checkExist = setInterval(function () {
        if (document.querySelectorAll(cssLocator).length == 0) {
            clearInterval(checkExist);
            console.log('waited until element not present.');
            return;
        } else if (endTime < new Date().getTime()) {
            clearInterval(checkExist);
            console.log('element still found after ' + timeoutInSeconds + ' seconds.');
            return;
        } else { 
            console.log('waiting for element not present ...'); 
        } 
    }, 100);
}

这是另一个等待元素出现的函数

function waitUntilElementPresent(cssLocator, timeoutInSeconds) {
    var currentTime = new Date().getTime();
    var endTime = currentTime + timeoutInSeconds * 1000;
    var checkExist = setInterval(function () {
        if (document.querySelectorAll(cssLocator).length) {
            clearInterval(checkExist);
            return;
        } else if (endTime < new Date().getTime()) {
            clearInterval(checkExist);
            console.log('not found in specified time.');
            return;
        } else {
            console.log('waiting for element to be present…');
        } 
    }, 100); 
}

【讨论】:

  • document.evaluate('/html/body/nav/section[4]/div/form[1]/input[4]', document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue 。点击();和 Window.Close 是我的脚本中最重要的两个方面,我将如何将它们植入您的代码以使计时器关闭网页?
  • 您必须为您的元素构建正确的 css,您能否分享表单和输入的 url 或 html。
【解决方案2】:

MutationObserver

我是这样用的

(function() {

    // monitor the page for changes and reapply if necessary
    // use 'observer.disconnect()' in 'fnCheckChanges()' to stop monitoring

    var alvo = document.querySelector('body');
    var observer = new MutationObserver(fnCheckChanges);
    observer.observe(alvo, { attributes: true, characterData: true, childList: true, subtree: true });

})();

function fnCheckChanges(changes, observer) {

    // your code here

    console.log('page changed');

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-01-12
    • 2015-08-29
    • 2019-12-14
    • 1970-01-01
    • 2022-08-12
    • 2011-10-23
    • 1970-01-01
    • 2021-12-21
    相关资源
    最近更新 更多