最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

html - JavaScript - wait until element loaded on website using Chrome extension - Stack Overflow

programmeradmin2浏览0评论

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 badges
Add a comment  | 

4 Answers 4

Reset to default 20

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
发布评论

评论列表(0)

  1. 暂无评论