问题描述
我收到 DOMException: Failed to read the 'cssRules' property from 'CSsstyleSheet': Cannot access rules 。任何建议我如何解决相同的问题。
示例代码
function copyStyles(source,target) {
Array.from(source.styleSheets).forEach(styleSheet => {
let rules
try {
rules = styleSheet.cssRules
} catch (err) {
console.error(err)
}
if (rules) {
const newStyleEl = source.createElement('style')
Array.from(styleSheet.cssRules).forEach(cssRule => {
.......
})
target.head.appendChild(newStyleEl)
} else if (styleSheet.href) {
..........
}
})
}
解决方法
我建议您避免调用可能通过 CSP 保护的 cssRules,而只需添加一个新样式表,其中包含您想要覆盖现有规则的任何规则。
像这样...
var S=document.createElement('style');
S.innerHTML='#Menu{background:red;} body{overflow:auto;}';
Frame_ID.contentWindow.document.body.appendChild(S);
,
根据 CORS 安全政策,您无法通过 javascript 访问从第三方域加载的资源内容。这也适用于 CSS 文件(尽管尚未在所有浏览器中实现)。
因此,如果 source.styleSheets
之一是第三方 CSS 文件,那么您将在尝试访问 cssRules
的 rules
或 stylesheet
属性时收到此错误}
顺便说一下,作为您正在尝试的解决方案,而不是在 else 部分创建链接标签,获取(通过 xhr 或 fetch
API)stylesheet.href
并且您将在JS 作为可以附加到 DOM 中的样式标签的文本。
示例
fetch(stylesheet.href)
.then(response => response.text())
.then(response => {
const st = document.createElement('style');
st.textContent = response;
document.body.append(st);
});