Chrome 扩展:如何获取网站 assets/resources(CSS、图片等)

Chrome Extension: How to get website assets/resources (CSS, Images etc)

我想开发一个 Chrome 扩展,读取 CSS 和网站图片。我想要实现的目标将具有 CSS Peeper https://csspeeper.com/ 之类的功能。 内容脚本背景脚本是否可行?我尝试寻找解决方案,但找不到我要找的东西。

manifest.json

{
"manifest_version": 2,
"name": "Get all css rules in stylesheets",
"background": {
  "scripts": ["background.js"],
  "persistent": true
 },
"permissions": ["activeTab", "tabs", "webRequest", "storage", "<all_urls>"],
"version": "1.0",
"page_action": {
"default_icon": {
  "16": "images/get_started16.png",
  "32": "images/get_started32.png",
  "48": "images/get_started48.png",
  "128": "images/get_started128.png"
 }
},
"icons": {
  "16": "images/get_started16.png",
  "32": "images/get_started32.png",
  "48": "images/get_started48.png",
  "128": "images/get_started128.png"
 }
}

我也试图挖掘 CSS Peeper 代码,但我只找到 background.js 文件:

/* CSS Peeper background.js file */
chrome.browserAction.onClicked.addListener(function () {
   chrome.tabs.executeScript({
       file: 'scripts/index.js'
   });
   chrome.tabs.insertCSS({
       file: 'styles/page.css'
   });
});

我认为您需要将 content_script 添加到 manifest.json,然后使用 document.styleSheets

阅读样式表
"content_scripts": [
  {
    "matches": ["<all_urls>"],
    "js" : ["myscript.js"],
    "run_at": "document_end"
  }
],

在您的 myscript.js 文件中使用 document.styleSheets 获取样式表。

阅读此内容了解更多详情:https://developer.chrome.com/extensions/content_scripts

Content scripts are files that run in the context of web pages. By using the standard Document Object Model (DOM), they are able to read details of the web pages the browser visits, make changes to them and pass information to their parent extension.

尽管上述答案在技术上是正确的,并且会 return 页面使用的样式表列表,但我建议使用不同的方法来获取页面的颜色和图像。

获取样式表只是解决方案的一部分,因为您随后需要读取它、解析它、从中查询颜色等,这很快就会变得极其复杂。

幸运的是,有一个 API 可以为您完成这一切:window.getComputedStyle()

下面是一个如何使用它从页面获取颜色的示例。

使用 javascript

从页面获取所有颜色
// Get all elements from page
const elements = document.querySelectorAll('*');
// Get computedStyles for each elements
const computedStyles = Array.from(elements).map(el => window.getComputedStyle(el));

const colors = computedStyles.map(styles => {
const keys = Object.values(styles);
const values = keys.map(key => styles.getPropertyValue(key));

// Get rgb & rgba colors from style values
const colors = values.map(value => {
    // Thanks to 
    const rgbColorRegEx = /rgba?\((\d+),\s*(\d+),\s*(\d+)(?:,\s*(\d+(?:\.\d+)?))?\)/ig;
    const rgbColors = value.match(rgbColorRegEx);

        return rgbColors || [];
    }).flat();

    return colors;
})
   .filter(colors => colors.length !== 0) // Remove empty results
   .flat() // Flatten resulting array
   .filter((el, index, arr) => arr.indexOf(el) === index); // Only keep unique results

此示例的方法相当幼稚,但可以轻松扩展以满足您的需要。您可以使用相同的技术来获得页面的任何其他样式。

使用 javascript

从页面获取每张图片

如上所述,您可以使用 document.querySelector('img, svg') 简单地查询页面上的图像,这将 return 页面上 svgimg 元素的节点列表.如果你也想获得背景图像,你可以使用与上面相同的技术,但匹配 background-image 而不是 rgb/rgba 值。