Eldest808
Eldest808

Reputation: 29

How to wait until element present in javascript?

(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();
})();

So the click function works but as soon as I add the Sleep windows.close no longer works? Im stil learning Javascript so can someone help please? All I want to do is have it click the Vote Up button then Close the active tab.

Upvotes: 1

Views: 3697

Answers (2)

yodog
yodog

Reputation: 6232

with MutationObserver

i use like this

(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');

}

Upvotes: 1

supputuri
supputuri

Reputation: 14135

Try this function which will wait while the element is present.

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);
}

Here is the other function that will wait until the element is present

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); 
}

Upvotes: 1

Related Questions