Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to run code when a dom element is added firefox extensions

I am making a extension that edits a element on a page but its only working if the element is on the page when it loads (with the website im using it will never happen) so i want to get a event if a div with the id of "427" shows up.

code:

var card = !!document.getElementById(427);
console.log(card);
if (card = true) {
    var card = document.getElementById(427)
    var cardimg = card.children.item(9)
    cardimg.setAttribute("style", 'background: transparent url("images/cards/Ultimate_Recipe.png") no-repeat scroll 0% 0%;')
};

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You could use MutationObserver, but you should be careful with memory usage:

const onMutation = () => {
  const element = document.getElementById(427)
  if (element) {
    observer.disconnect()
    elementIsReady(element)
  }
}

const observer = new MutationObserver(onMutation)

observer.observe(document.body, {childList: true, subtree: true})

You could also use Promise, by querying each x ms:

new Promise(async (resolve) => {
  let element
  while (!(element = document.getElementById(427))) await new Promise(r => setTimeout(r, 200))
  resolve(element)
}).then(elementIsReady)
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading