JavaScript - wait until element loaded on website using Chrome extension

Viewed 3883

I'm developing a Chrome extension that clicks elements on a website, but some of the elements appear after the check and the code doesn't work. I need to make the function wait until the selected element is loaded.

And NOT wait in delays in seconds like on setTimeout function.

How can I do it?

4 Answers

Can be done with MutationObserver:

function handleSomeDiv(someDiv) { 
    console.log("div was handled");
}

const observer = new MutationObserver(function (mutations, mutationInstance) {
    const someDiv = document.getElementById('some-div');
    if (someDiv) {
        handleSomeDiv(someDiv);
        mutationInstance.disconnect();
    }
});


observer.observe(document, {
    childList: true,
    subtree:   true
});
let element = document.getElementById('elementId')
while (element === null) {
    console.log('Waiting for element')
    element = document.getElementById('elementId')
}

// Perform operation with element

There are 2 ways to do this:

window.onload:

HTML:

<p id="pElement">Hello</p>

Javascript:

window.onload = () => {
  document.getElementById("pElement").innerHTML+=", world!"
}

document.addEventListener('load')

HTML:

<p id="pElement">Hello</p>

Javascript:

document.addEventListener('load',()=>{
  document.getElementById("pElement").innerHTML += ", world!";
});;
  • You can try setInterval this method will be working all the time in the page and when your condition is true it's will execute it but be careful when use it - because of this method will be working all the time in the page so you need to add condition to exacute it just one time

Example

var check = false;
setInterval(function () {
   if(document.getElementById("id") !== null && check === false) {
        document.getElementById("id").click();
        check = true;
    }
}, 1000)
  • this will be check every second and when you condition is true it's will execute it just one time
  • if you removed check condition it's will execute this code every second
Related