【问题标题】:javascript append to DOM before DOM is constructed (head and body are null)javascript 在构造 DOM 之前附加到 DOM(head 和 body 为空)
【发布时间】:2021-08-23 07:49:37
【问题描述】:

目标:隐藏 youtube 推荐

实现:注入

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)

在这里,我在构建 DOM 之后附加到头部,这可行,但我看到 yt 建议在它们被隐藏之前 0.5 秒


所以我尝试在构造 DOM 之前追加,但是

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
文档开始
字符串
脚本是在任何来自 css 的文件之后,但在构造任何其他 DOM 或运行任何其他脚本之前注入的。

我的 javascript 在内容脚本中

【问题讨论】:

标签: javascript html css dom google-chrome-extension


【解决方案1】:

<html> 元素本身可能存在。它在语义上不正确,但您可以附加到它,它会根据需要应用 CSS 规则。

document.documentElement.appendChild(styleEl);

另一种选择是将 MutationObserver 添加到 <html> 并在出现 <head><body> 时追加。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-06
    • 2016-02-13
    • 1970-01-01
    • 2016-12-24
    • 2013-10-12
    • 1970-01-01
    相关资源
    最近更新 更多