Search code examples
javascripthtmlcssdomgoogle-chrome-extension

javascript append to DOM before DOM is constructed (head and body are null)


Goal: hide youtube recommendations

Implementation: inject <style> to hide some css classes

var styleEl = document.createElement('style')
styleEl.textContent = `ytd-rich-grid-renderer,ytd-watch-next-secondary-results-renderer,ytd-comments,ytd-live-chat-frame{
  display:none !important
}`
document.head.appendChild(styleEl)

here, I append to head AFTER DOM is constructed, this works, but I see yt recommendations for 0.5 seconds before they are hidden


so I try to append BEFORE DOM is constructed, but

console.log(document.head) //null
console.log(document.body) //null
document.appendChild(styleEl) // Uncaught DOMException: Failed to execute 'appendChild' on 'Node': Only one element on document allowed

https://developer.chrome.com/docs/extensions/mv3/content_scripts/#run_time
document_start
string
Scripts are injected after any files from css, but before any other DOM is constructed or any other script is run.

my javascript is inside a content script


Solution

  • The <html> element itself may exist. It's not semantically proper, but you can append to it instead, and it will apply the CSS rules as desired.

    document.documentElement.appendChild(styleEl);
    

    Another option would be to add a MutationObserver to the <html> and append once the <head> or <body> appear.