0

I'm trying to use execute a simple querySelector inside a contentscript of my chrome extension:

const el = document.querySelector("#sections > ytd-guide-section-renderer:nth-child(1)");
console.log(el);

When visiting the main youtube page the querySelector works fine and I get my result. However when visiting the "subs" or "trends" page the querySelector returns null. Executing the script manually inside the console works fine.

console.log(document.body) also works on the subs/trends pages. I also tried adding a delay but that didn't really help at all.

For testing purposes I added "matches": ["<all_urls>"] so the script should be able to run on any site.

Any ideas?

Lars
  • 39
  • 10
  • If `querySelector` is returning `null`, then no elements that match the selector are in the DOM *as of when you run that code*. (They may be added later, which would explain why running it manually would work.) – T.J. Crowder Jun 06 '19 at 13:16
  • Okay, I added a delay of 5 seconds, looks like the querySelector is working now. Thanks for your help! :) – Lars Jun 06 '19 at 13:18
  • No worries! FWIW, I wouldn't use a delay. I'd probably use `setTimeout` when I saw `null` to try again 50-100ms later, or watch for DOM mutation on the container element. – T.J. Crowder Jun 06 '19 at 13:26
  • Thanks, I've just included a setTimeout and change the delay depending on the current network connection. – Lars Jun 06 '19 at 20:09

0 Answers0