Chrome插件开发:在网页上运行脚本
金金金上线!
话不多,只讲你能听懂的前端知识
概览
- 本教程将构建一个扩展程序,用于向任何 Chrome 扩展程序和 Chrome 应用商店文档页面添加预计阅读时间
构建扩展程序
- 创建一个名为
reading-time
的新目录来存放扩展程序的文件
添加扩展程序的相关信息
- 清单 JSON 文件是唯一的必需文件。其中包含有关扩展程序的重要信息。在项目的根目录中创建一个
manifest.json
文件,并添加以下代码:{"manifest_version": 3,"name": "Reading time","version": "1.0","description": "Add the reading time to Chrome Extension documentation articles" }
- 它必须位于项目的根目录中
- 唯一的必需键是
"manifest_version"
、"name"
和"version"
。 - 它在开发期间支持注释 (
//
),但您必须先移除这些注释,然后才能将代码上传到 Chrome 应用商店。
提供图标
- 那么,为什么需要图标?虽然在开发过程中图标是可选的,但如果打算在 Chrome 应用商店中分发扩展程序,则必须提供图标。它们还会显示在扩展程序管理页面等其他位置。
- 创建一个
images
文件夹,并将图标放入其中(自行下载就好):
声明内容脚本
-
扩展程序可以运行脚本,以读取和修改网页内容。这些脚本称为内容脚本。它们位于隔离的世界中,这意味着它们可以更改自己的 JavaScript 环境,而不会与其托管页面或其他扩展程序的内容脚本发生冲突。
-
将以下代码添加到
manifest.json
以注册名为content.js
的内容脚本:"content_scripts": [{"js": ["scripts/content.js"],"matches": ["https://developer.chrome.com/docs/extensions/*","https://developer.chrome.com/docs/webstore/*"]}]
"matches"
字段可以有一个或多个匹配模式。这些标记可让浏览器确定要将内容脚本注入哪些网站。匹配模式由以下三个部分组成:<scheme>://<host><path>
。可以包含“*
”字符。
计算并插入阅读时间
-
内容脚本可以使用标准文档对象模型 (DOM) 读取和更改网页内容。该扩展程序首先会检查网页是否包含
<article>
元素。然后,它会统计此元素中的所有字词,并创建一个段落来显示总阅读时间。在名为
scripts
的文件夹中创建一个名为content.js
的文件,然后添加以下代码:function renderReadingTime(article) {// If we weren't provided an article, we don't need to render anything.if (!article) {return;}const text = article.textContent;const wordMatchRegExp = /[^\s]+/g; // Regular expressionconst words = text.matchAll(wordMatchRegExp);// matchAll returns an iterator, convert to array to get word countconst wordCount = [...words].length;const readingTime = Math.round(wordCount / 200);const badge = document.createElement("p");// Use the same styling as the publish information in an article's headerbadge.classList.add("color-secondary-text", "type--caption");badge.textContent = `⏱️ ${readingTime} min read`;// Support for API reference docsconst heading = article.querySelector("h1");// Support for article docs with dateconst date = article.querySelector("time")?.parentNode;(date ?? heading).insertAdjacentElement("afterend", badge); }renderReadingTime(document.querySelector("article"));
测试是否生效
加载扩展程序,访问:https://developer.chrome.com/docs/extensions/get-started/tutorial/scripts-on-every-tab?hl=zh-cn
- 这样便是成功了
编写有误还请各位指正,万分感谢。