javascriptcode-injection

Cannot wait until the entire DOM is loaded with Scripty Chrome extension


I've used the Scripty extension to inject some JS code in a page which aims to notify me whether a certain string is present in a table.

The code detection code seems to work fine. I've tried to launch a snippet via Chrome which works, but through this extension it doesn't seem to work.

I strongly believe it's a matter of the DOM not being completely loaded, since outputting the size of my querySelectorAll() result gives me 0.

I've tried different approaches like document.onload or document.onreadystatechange or selecting the option to run my code on page load (through Scripty extension). This is my code

window.onload = function() {
  if (Notification.permission !== 'granted') {
    console.log("permission is not granted!")
    Notification.requestPermission()
  }

  let available = document.querySelectorAll("td")
  let availableCondition = true;
  
  for (let index = 0; index < available.length; index++) {
    console.log(available[index].innerText)
    if (available[index].innerText.toLowerCase().includes('la sede non offre')) {
      availableCondition = false
      break
    }
  }

  if (availableCondition) {
    new Notification("Appuntamento disponibile")
  } else 
    location.reload()
}

Solution

  • To run your code once the DOM is ready, use the DOMContentLoaded event:

    document.addEventListener("DOMContentLoaded", (event) => {
      console.log("DOM fully loaded and parsed");
    });
    

    See https://developer.mozilla.org/en-US/docs/Web/API/Document/DOMContentLoaded_event