我的chrome扩展程序需要修改用户页面上的某些css规则.document.styleSheets仅通过访问样式可以访问从同一域中链接的样式.document.styleSheets数组的其他元素已cssRules/rules设置为null.
为什么跨域政策适用于此?无论其来源如何,都会使用样式,那么重点是什么?以及如何解决这个问题?
编辑:
我需要修改用户css规则(而不是简单地添加我自己的规则)的原因是我需要保护扩展注入的自定义元素不受*规则的影响.看到这个问题的细节
这是代码:
你会注意到alert(document.styleSheets[x].cssRules.length)失败的"安全例外".任何解决方法.我问,因为有一些"CSS延迟加载"类使用此功能来检测是否加载了CSS文档.
另外:安全例外是正确的行为/是否符合标准?
我正在编写一个chrome扩展,需要迭代注入页面中的所有样式表并修改某些样式.
我迭代/修改样式,例如:
const iterate = (doc, f) => {
for (const styleSheet of doc.styleSheets) {
const rules = styleSheet.rules || styleSheet.cssRules;
if (!rules) continue;
for (const cssRule of rules) {
if (!cssRule.style) continue;
const selector = cssRule.selectorText, style = cssRule.style;
if (!selector || !style.cssText) continue;
f(style);
}
}
}
document.addEventListener("DOMContentLoaded", e => {
setTimeout(() => {
iterate(document, style => {
if (style.getPropertyValue('background-color')) style.setProperty('background-color', 'yellow');
});
}, 1000);
});Run Code Online (Sandbox Code Playgroud)
div {
background-color: red;
}Run Code Online (Sandbox Code Playgroud)
<div>hello</div>Run Code Online (Sandbox Code Playgroud)
我遇到的问题是外部css似乎没有被包括在内.
例如,如果我将我的扩展注入stackoverflow.com,它具有:
<link rel="stylesheet" type="text/css" href="https://cdn.sstatic.net/Sites/stackoverflow/all.css?v=cfd0b49a38a7"> …Run Code Online (Sandbox Code Playgroud) 注意:此更新如下.我可能会更改描述,因为它不是getComputedStyle问题,实际上是打印媒体的问题,而且Internet Explorer现在支持document.styleSheets [].cssRules这一事实.
我对此感到有些困惑,因为我觉得这很有效,我不确定它最近是否破产了.我正在使用getComputedStyle,我认为它支持所有现代浏览器,但我没有得到IE 11的预期答案.鉴于此代码:
getRealStyle: function(elm, attributes) {
var returnObj = {};
var computed = getComputedStyle(elm);
for(var i=0; i<attributes.length; i++) {
returnObj[attributes[i]] = computed[attributes[i]];
}
return returnObj;
},
Run Code Online (Sandbox Code Playgroud)
其中"attributes"是一个名称数组,我有兴趣获取计算的CSS.它是这样的:
attributes: [
'lineHeight',
'alignmentBaseline',
'backgroundImage', 'backgroundPosition', 'backgroundRepeat', 'backgroundColor',
'baselineShift',
'borderTopWidth','borderTopStyle','borderTopColor',
'borderBottomWidth','borderBottomStyle','borderBottomColor',
'borderLeftWidth','borderLeftStyle','borderLeftColor',
'borderRightWidth','borderRightStyle','borderRightColor',
'borderCollapse',
'clear', 'color',
'display', 'direction', 'dominantBaseline',
'fill', 'float',
'fontStyle', 'fontVariant', 'fontWeight', 'fontSize', 'fontFamily',
'height',
'listStyleType', 'listStyleImage',
'marginTop', 'marginBottom', 'marginLeft', 'marginRight','orphans',
'paddingTop', 'paddingRight', 'paddingBottom', 'paddingLeft',
'pageBreakAfter', 'pageBreakBefore',
'stroke', 'strokeWidth',
'strokeOpacity', 'fillOpacity',
'tableLayout',
'textAlign', 'textAnchor','textDecoration', 'textIndent', 'textTransform', 'textShadow', …Run Code Online (Sandbox Code Playgroud)