Wei Zhang
Wei Zhang

Reputation: 325

Is there any way to check the DOM element every few seconds in content.js in chrome extension?

I am manipulating the DOM from my content.js in chrome extension. The webpage would be changed after an uncertain time. I would like to write some codes to monitor the change. That means I would like to do something after I found the DOM changed. Is there any way to check the DOM every few time or seconds in content.js? I have not done this before. Thanks for any suggestion.

Upvotes: 0

Views: 515

Answers (1)

tiagolisalves
tiagolisalves

Reputation: 533

Other way not so elegant like MutationObserver is to use setInterval to execute code periodically:

setInterval(()=> {
 let d = document.querySelector('#el')
 if(d){
  console.log('dom manipulation')
 }
},100)

Every 100 ms the function is executed.

To stop the interval, you have to save the return of setInterval to a variable. You pass this value to the global function clearInterval to stop the interval:

let interval = null

let domWorks = () => {
     let d = document.querySelector('#el')
     if(d){
      console.log('dom manipulation')
      clearInterval(interval) // Change it via reference
     }
}

interval = setInterval(domWorks, 100)

You can create a function that encapsulates the interval and execute some callback when some condition is true:

  const executeWhenItsReady = (testCondition, callbackToExecute) => {
      let interval = null;
      let tryToExecute = () => {
        let result = testCondition();
        console.log("trying again");
        if (result) {
          callbackToExecute();
          clearInterval(interval); // Change it via reference
        }
      };

      interval = setInterval(tryToExecute, 100);
    };

  executeWhenItsReady(
         () => document.querySelector("el"), 
         () => console.log("dom manipulation")
  );

Upvotes: 1

Related Questions