【Chrome Extension】一、CSDN计时扩展设计
【Chrome Extension】一、CSDN计时扩展设计
- 重点内容
- 内容脚本 content_scripts
- 文件目录
- 1、整体目录
- 2、manifest.json
- 3、scripts/content.js
- 4、css/content.css
重点内容
内容脚本 content_scripts
1、manifest.json文件配置
{
"manifest_version": 3, # *依赖Chrome插件版本
"name": "FeiFeiYeChuan-Tools-CSDN Article Reading Time", # *插件名称
"version": "1.0", # *插件版本
"description": "Add the reading time to Chrome Extension documentation articles",
"icons": { # 不同情况下显示的图标
"16": "images/logo.png",
"32": "images/logo.png",
"48": "images/logo.png",
"128": "images/logo.png"
},
"content_scripts": [ # content内容
{
"js": [
"scripts/content.js"
],
"css": [
"css/content.css"
],
"matches": [
"https://*.blog.csdn.net/*",
"https://blog.csdn.net/*"
]
}
]
}
如上 content_scripts
(内容脚本:运行读取和修改网页内容的脚本
) 主要用于在固定 matches 网页下的执行脚本内容,他们独立于其他扩展程序和托管页面,拥有独立的js,css脚本。
文件目录
1、整体目录
2、manifest.json
{
"manifest_version": 3,
"name": "FeiFeiYeChuan-Tools-CSDN Article Reading Time",
"version": "1.0",
"description": "Add the reading time to Chrome Extension documentation articles",
"icons": {
"16": "images/logo.png",
"32": "images/logo.png",
"48": "images/logo.png",
"128": "images/logo.png"
},
"content_scripts": [
{
"js": [
"scripts/content.js"
],
"css": [
"css/content.css"
],
"matches": [
"https://*.blog.csdn.net/*",
"https://blog.csdn.net/*"
]
}
]
}
3、scripts/content.js
onload = function () {
console.log("content.js已加载");
const article = document.querySelector(".blog-content-box");
console.log('article:', article)
// `document.querySelector` may return null if the selector doesn't match anything.
if (article) {
const text = article.textContent;
// console.log('text:', text)
const wordMatchRegExp = /\w/g; // Regular expression
const words = text.matchAll(wordMatchRegExp);
// matchAll returns an iterator, convert to array to get word count
const wordCount = [...words].length;
console.log("wordCount:", wordCount)
const readingTime = Math.round(wordCount / 200);
const badge = document.createElement("p");
// Use the same styling as the publish information in an article's header
badge.classList.add("color-secondary-text", "type--caption", 'light');
badge.textContent = `⏱️ ${readingTime} min read`;
// Support for API reference docs
const heading = document.querySelector(".title-article");
heading.insertAdjacentElement("afterend", badge);
}
}
4、css/content.css
.light{
color: #77a000;
}