[英]Make <Style> block !important using javascript?
I am trying to make a chrome extension that overrides the style used by a webpage of my choice.我正在尝试制作一个 chrome 扩展来覆盖我选择的网页所使用的样式。 I have already figured out how to change the style using javascript, though when the page loads, the a brief moment when you can see the original page.
我已经想出了如何使用 javascript 更改样式,但是当页面加载时,您可以看到原始页面的短暂时间。 I tried setting the manifest file to run at document start, but that just had my css get overwritten with the original page.
我尝试将清单文件设置为在文档开始时运行,但这只是让我的 css 被原始页面覆盖。 How do I go about this?
我该怎么做?
const addStyle = (() => {
const style = document.createElement('style');
document.head.append(style);
return (styleString) => style.textContent = styleString;
})();
Assuming you already artificially increased CSS specificity , there are two more methods:假设您已经人为地增加了 CSS specificity ,还有两种方法:
Make the style element the last sheet in DOM by placing it after body
as a direct child of html
.通过将 style 元素作为
html
的直接子元素放置在body
之后,使 style 元素成为 DOM 中的最后一张表。
It's a perfectly valid DOM tree per DOM specification so we can disregard the fact it violates HTML specification as that's irrelevant for the browser use case and doesn't cause any adverse effects.对于每个 DOM 规范,它是一个完全有效的 DOM 树,因此我们可以忽略它违反 HTML 规范的事实,因为这与浏览器用例无关,并且不会造成任何不利影响。
manifest.json:清单.json:
content_scripts
should have "run_at": "document_start" content_scripts
应该有"run_at": "document_start" content.js:内容.js:
const styles = [];
const appendToRoot = el => document.documentElement.append(el);
const addStyle = (() => {
const style = document.createElement('style');
appendToRoot(style);
if (!document.body) styles.push(style);
return (styleString) => style.textContent = styleString;
})();
if (document.body) {
onBody();
} else {
new MutationObserver((_, observer) => {
if (document.body) {
observer.disconnect();
onBody();
}
}).observe(document.documentElement, {childList: true});
}
function onBody() {
// move them after body
styles.forEach(appendToRoot);
styles.length = 0;
}
user
user
A user-originated rule with !important
wins over author-originated rule with !important
( MDN ) so if your CSS has !important
on all of its rules, use chrome.tabs.insertCSS with cssOrigin: 'user'
from the background script in a listener for chrome.webNavigation.onCommitted , for example.带有
!important
用户起源规则胜过带有!important
( MDN ) 的作者起源规则,所以如果你的 CSS 在它的所有规则上都有!important
,使用chrome.tabs.insertCSS和cssOrigin: 'user'
from the background script in例如, chrome.webNavigation.onCommitted的侦听器。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.