跳到主要内容

在每个网页上运行脚本

概述

本次实现一个在网页上插入新元素的扩展程序。

功能描述

能够在每个页面后台执行,自动获取页面上的 article 标签,并计算阅读时长,最后插入在 article 内容的末端。

效果图:

开发

创建项目:

mkdir reading-time
cd reading-time
touch manifest.json

一、给 manifest.json 添加基础信息:

{
"manifest_version": 3,
"name": "Reading time",
"version": "1.0",
"description": "Add the reading time to Chrome Extension documentation articles"
}

二、添加图标信息:

{
"icons": {
"16": "images/icon-16.png",
"32": "images/icon-32.png",
"48": "images/icon-48.png",
"128": "images/icon-128.png"
}
}

注:不同尺寸的图标显示位置:

  • 16:扩展程序页面和上下文菜单中的图标
  • 32:Windows 计算机通常需要此大小
  • 48:显示在“扩展程序”页面上
  • 128:会在安装过程中和 Chrome 应用商店中显示

三、声明脚本:

{
"content_scripts": [
{
"js": ["scripts/content.js"],
"matches": [ // 匹配域名`<scheme>://<host><path>`
"https://developer.chrome.com/docs/extensions/*",
"https://developer.chrome.com/docs/webstore/*"
]
}
]
}

四、实现脚本

const article = document.querySelector('article');

if (article) {
const text = article.textContent;
const wordMatchRegExp = /[^\s]+/g;
const words = text.matchAll(wordMatchRegExp);
const wordCount = [...words].length;
const readingTime = Math.round(wordCount / 200);
const badge = document.createElement('p');

badge.classList.add('color-secondary-text', 'type--caption');
badge.textContent = `⏱️ ${readingTime} min read(🤔)`;

const heading = article.querySelector('h1');
const date = article.querySelector('time')?.parentNode;

if (date || heading) {
(date ?? heading).insertAdjacentElement('afterend', badge);
}
}

五、在浏览器加载扩展测试

打开 https://developer.chrome.com/docs/extensions/reference/api?hl=zh-cn 验证:

成功啦!

完整目录结构及代码资源:

reading-time
├── images
│ ├── icon-128.png
│ ├── icon-16.png
│ ├── icon-32.png
│ └── icon-48.png
├── manifest.json
└── scripts
└── content.js

DEMO: chrome-extension-demos/02/reading-time

资源

参考