问题描述
我的 chrome 扩展需要修改用户页面上的某些 css 规则.通过 document.styleSheets
访问样式只能访问从同一域内链接的样式.document.styleSheets
数组的其他元素将 cssRules/rules
设置为 null.
My chrome extension needs to modify certain css rules on user's page. Accessing styles via document.styleSheets
only gives access to styles linked from within the same domain. Other elements of document.styleSheets
array have cssRules/rules
set to null.
为什么跨域策略适用于此?无论如何,样式都会被应用,而不管它们的来源,那有什么意义呢?在我的情况下如何解决它?
Why is it cross domain policy applies here? Styles are being applied anyway regardless of their origin, so what is the point? And how to get around it in my case?
我需要修改用户 css 规则(而不是简单地添加我自己的规则)的原因是我需要保护扩展注入的自定义元素不受 *
规则的影响.查看此问题的详细信息
The reason I need to MODIFY user css rules (as opposed to simply adding my own) is that I need to protect custom element injected by extension from being affected by *
rules. see details in this question
推荐答案
与常规 javascript 相比,内容脚本没有任何跨域权限,因此任何限制都被保留了下来.请参阅相关问题#1,问题#2.
Content scripts don't have any cross-domain privileges comparing to a regular javascript, so any limitations are carried over. See related question #1, question #2.
您可以在清单中注入自己的 css 样式:
You can inject your own css style in the manifest:
"content_scripts": [
{
"matches": ["http://www.google.com/*"],
"css": ["mystyles.css"]
}
]
您可以通过定义具有更高特异性的规则来尝试覆盖原始样式.
where you can try to overwrite original styles by defining rules with higher specificity.
您也可以通过 javascript 调整具体元素样式:
You can also just tweak concrete element styles through javascript:
document.getElementById("id").style.property="value";
这篇关于cssRules/rules 在 Chrome 中为 null的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!