【问题标题】:JavaScript: (How) can one retrieve external CSS rules in Chrome's DevTools?JavaScript:(如何)可以在 Chrome 的 DevTools 中检索外部 CSS 规则?
【发布时间】:2023-03-06 11:27:01
【问题描述】:
我正在开发一个扩展其 DevTools 的小 Chrome 扩展程序。为此,我需要为当前选定的元素 ($0) 获取所有已定义的 CSS 选择器。
我知道document.styleSheets 中的每个项目都通过cssRules 公开所有必要的数据。这将是完美的,但不幸的是,CORS 似乎在工作中扔了一把扳手。对于外部样式表,cssRules 返回null。
是否可以在不求助于黑客解决方案的情况下访问这些数据,例如下载样式表并将其插入style 标记?我问是因为 Chrome 本身似乎在其 Styles 侧边栏面板中这样做,但我找不到关于此事的太多信息。
谢谢!
【问题讨论】:
标签:
javascript
css
google-chrome
cors
google-chrome-devtools
【解决方案1】:
我想我已经明白了。只是在文档中进行了更多挖掘。
inspectedWindow API 公开了getResources,允许您获取检查窗口内的所有资源。这包括获取其内容的类型和功能。
将此内容注入style 标记可让您通过document.styleSheets 访问CSS 规则。这是理想的,因为我的侧边栏窗格被封装在一个影子 DOM 中,让我可以准确地知道注入了哪些样式表。
chrome.devtools.inspectedWindow.getResources(function(resources) {
for (var i = 0; i < resources.length; i++) {
if (resources[i].type != 'stylesheet') {
continue;
}
// inject the resource into the shadow DOM
// this allows us to freely access all CSS rules CORS-free
resources[i].getContent(function(content) {
var style = document.createElement('style');
style.textContent = content;
document.body.appendChild(style);
});
}
});