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?
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?
Share Improve this question edited Sep 21, 2022 at 22:23 kahlan88 1011 silver badge8 bronze badges asked Jul 10, 2021 at 16:01 Denny callàDenny callà 1451 gold badge2 silver badges8 bronze badges4 Answers
Reset to default 20Can 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