关于前端:译Chrome-扩展-入门

8次阅读

共计 7131 个字符,预计需要花费 18 分钟才能阅读完成。

引子

依照 Chrome 扩大 : 扩大是什么? 中疏导,接着就是入门教程。

  • 原文:Getting started
  • 版本:Updated on Wednesday, November 18, 2020
  • 源库:developer.chrome.com GitHub
  • Origin
  • My GitHub

入门

扩大由不同但内聚的组件组成。组件能够包含后盾脚本、内容脚本、选项页、UI 元素和各种逻辑文件。扩大组件是应用 web 开发技术创立的:HTML、CSS 和 JavaScript。扩大的组件将取决于其性能,可能不须要所有选项。

刚开始,创立一个新文件夹用来寄存扩大的文件。

残缺的扩大能够在这里下载。

创立 manifest

扩大从 manifest 开始。创立一个名为 manifest.json 文件并蕴含以下代码。

{
  "name": "Getting Started Example",
  "description": "Build an Extension!",
  "version": "1.0",
  "manifest_version": 3
}

在以后状态下,能够在开发人员模式下将蕴含 manifest 文件的目录增加为扩大。

  1. 导航到 chrome://extensions 关上扩大治理页面。

    • 或者点击扩大菜单按钮,抉择菜单底部的 Manage Extensions 关上这个页面。
    • 或者点击 Chrome 菜单,悬浮在 More Tools 之后抉择 Extensions
  2. 点击 Developer mode 旁边的开关,开启开发者模式。
  3. 点击 Load unpacked 按钮,并抉择扩大文件夹。

嗒嗒!已胜利装置扩大。因为在 manifest 中没有蕴含图标,所以将为扩大创立一个通用图标。

增加性能

当初曾经装置了扩大,然而它当初什么做不了,因为咱们还没有通知它做什么或者什么时候做。咱们通过增加一些代码来存储背景色值来解决这个问题。

为此,咱们须要创立一个后盾脚本并将其增加到扩大的 manifest 中。首先在扩大的目录中创立一个名为 background.js 的文件。

{
  "name": "Getting Started Example",
  "description": "Build an Extension!",
  "version": "1.0",
  "manifest_version": 3,
+ "background": {
+   "service_worker": "background.js"
+ }
}

与许多其它重要组件一样,后盾脚本必须在 manifest 中注册。在 manifest 中注册一个后盾脚本会通知扩大要援用哪个文件,以及该文件的行为。

Chrome 当初意识到扩大蕴含一个服务。当你从新加载扩大时,Chrome 将扫描指定的文件以获取附加指令,例如须要侦听的重要事件。

这个扩大一旦装置,就须要来自长久变量的信息。首先在后盾脚本中蕴含一个对 runtime.onInstalled 的监听。在 onInstalled 侦听器中,扩大将应用 storage API 设置一个值。这将容许多个扩大组件拜访该值并更新它。

let color = '#3aa757';

chrome.runtime.onInstalled.addListener(() => {chrome.storage.sync.set({ color});
  console.log('Default background color set to %cgreen', `color: ${color}`);
});

大多数的 API,包含 storage API,必须在 manifest 中的 permissions 字段下注册,扩大能力应用它们。

{
  "name": "Getting Started Example",
  "description": "Build an Extension!",
  "version": "1.0",
  "manifest_version": 3,
  "background": {"service_worker": "background.js"},
+ "permissions": ["storage"]
}

返回到扩大治理页面,点击 Reload 链接。一个新的字段 Inspect views 可用,它有一个蓝色的链接:background page

点击链接查看后盾脚本输入的日志:”Default background color set to green”

译者备注

在 Chrome 版本 90.0.4430.85(正式版本)(x86_64) 中试了一下,发现有些出入的中央:

  • 可点击的链接是 Service Worker,而且在肯定的工夫后会变成 有效 ,所以须要点击 Reload 链接。

引入用户界面

扩大能够有多种形式的用户界面;这一种将应用 popup。创立并增加名为 popup.html 的文件到扩大的目录。此扩大应用按钮更改背景色。

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="button.css">
  </head>
  <body>
    <button id="changeColor"></button>
  </body>
</html>

与后盾脚本一样,这个文件必须在 manifest 中申明,以便 Chrome 在扩大弹出窗口中显示它。为此,向 manifest 增加一个 action 对象并设置 popup.html 作为 actiondefault_popup 属性值。

{
  "name": "Getting Started Example",
  "description": "Build an Extension!",
  "version": "1.0",
  "manifest_version": 3,
  "background": {"service_worker": "background.js"},
  "permissions": ["storage"],
+ "action": {
+   "default_popup": "popup.html"
+ }
}

这个弹出窗口的 HTML 援用了一个名为 button.css 的 CSS 文件。将另一个文件增加到扩大的目录中,适当地命名它,并增加以下代码。

button {
  height: 30px;
  width: 30px;
  outline: none;
  margin: 10px;
  border: none;
  border-radius: 2px;
}

button.current {
  box-shadow: 0 0 0 2px white,
              0 0 0 4px black;
}

工具栏图标的指定也蕴含在 actiondefault_icons 字段下。在这里下载图片文件,解压它,并将它放在扩大的目录中。更新 manifest,使扩大晓得如何应用图片。

{
  "name": "Getting Started Example",
  "description": "Build an Extension!",
  "version": "1.0",
  "manifest_version": 3,
  "background": {"service_worker": "background.js"},
  "permissions": ["storage"],
  "action": {
    "default_popup": "popup.html",
+   "default_icon": {
+     "16": "/images/get_started16.png",
+     "32": "/images/get_started32.png",
+     "48": "/images/get_started48.png",
+     "128": "/images/get_started128.png"
+   }
  }
}

扩大还能够在扩大治理页、权限正告和 favicon 上显示图像。这些图像在 manifest 的 icons 字段下指定。

{
  "name": "Getting Started Example",
  "description": "Build an Extension!",
  "version": "1.0",
  "manifest_version": 3,
  "background": {"service_worker": "background.js"},
  "permissions": ["storage"],
  "action": {
    "default_popup": "popup.html",
    "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"
+ }
}

如果在此阶段从新加载扩大,它将蕴含提供的图标而不是默认占位符,单击该操作将关上一个带有默认色彩按钮的弹出窗口。

弹出 UI 的最初一步是向按钮增加色彩。在扩大目录中创立名 popup.js 的文件,并增加以下代码。

// Initialize button with user's preferred color
let changeColor = document.getElementById("changeColor");

chrome.storage.sync.get("color", ({ color}) => {changeColor.style.backgroundColor = color;});

这个代码从 popup.html 中抓取按钮,并从存储中申请色彩值。而后将色彩作为按钮的背景。在 popup.html 中增加一个指向 popup.js 脚本标签。

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="button.css">
  </head>
  <body>
    <button id="changeColor"></button>
+   <script src="popup.js"></script>
  </body>
</html>

从新加载扩大查看绿色按钮。

逻辑层

扩大当初有一个自定义图标和一个弹出窗口,它依据保留到扩大存储中的值为弹出窗口按钮着色。接下来,它须要进一步的用户交互逻辑。在 popup.js 文件开端增加以下内容。

// When the button is clicked, inject setPageBackgroundColor into current page
changeColor.addEventListener("click", async () => {let [tab] = await chrome.tabs.query({active: true, currentWindow: true});

  chrome.scripting.executeScript({target: { tabId: tab.id},
    function: setPageBackgroundColor,
  });
});

// The body of this function will be executed as a content script inside the
// current page
function setPageBackgroundColor() {chrome.storage.sync.get("color", ({ color}) => {document.body.style.backgroundColor = color;});
}

更新后的代码向按钮增加了一个 click 事件监听器,该监听器触发一个以编程形式注入的内容脚本。这将使页面的背景色与按钮的色彩雷同。应用编程注入容许用户调用内容脚本,而不是将不须要的代码主动插入网页。

manifest 将须要 activeTab 权限来容许扩大长期拜访当前页,并且须要 scripting 权限来应用脚本 API 的 executeScript 办法。

{
  "name": "Getting Started Example",
  ...
+ "permissions": ["storage", "activeTab", "scripting"],
  ...
}

扩大当初性能实现了!从新加载扩大,刷新此页面,关上弹出窗口并单击按钮将其变为绿色!然而,有些用户可能心愿将背景更改为不同的色彩。

为用户提供选项

该扩大目前只容许用户将背景更改为绿色。蕴含一个选项页面能够让用户更好地管制扩大的性能,进一步定制他们的浏览体验。

首先在目录创立一个名 options.html 的文件并蕴含以下代码。

<!DOCTYPE html>
<html>
  <head>
    <link rel="stylesheet" href="button.css">
  </head>
  <body>
    <div id="buttonDiv">
    </div>
    <div>
      <p>Choose a different background color!</p>
    </div>
  </body>
  <script src="options.js"></script>
</html>

在 manifest 中注销选项页面。

{
  "name": "Getting Started Example",
  ...
+ "options_page": "options.html"
}

从新加载并点击 DETAILS

向下滚动详情页面并抉择 Extension options 以查看选项页面。

最初一步是增加选项逻辑。在扩大的目录中创立一个名为 options.js 的文件并增加以下代码。

let page = document.getElementById("buttonDiv");
let selectedClassName = "current";
const presetButtonColors = ["#3aa757", "#e8453c", "#f9bb2d", "#4688f1"];

// Reacts to a button click by marking the selected button and saving
// the selection
function handleButtonClick(event) {
  // Remove styling from the previously selected color
  let current = event.target.parentElement.querySelector(`.${selectedClassName}`
  );
  if (current && current !== event.target) {current.classList.remove(selectedClassName);
  }

  // Mark the button as selected
  let color = event.target.dataset.color;
  event.target.classList.add(selectedClassName);
  chrome.storage.sync.set({color});
}

// Add a button to the page for each supplied color
function constructOptions(buttonColors) {chrome.storage.sync.get("color", (data) => {
    let currentColor = data.color;
    // For each color we were provided…
    for (let buttonColor of buttonColors) {
      // …create a button with that color…
      let button = document.createElement("button");
      button.dataset.color = buttonColor;
      button.style.backgroundColor = buttonColor;

      // …mark the currently selected color…
      if (buttonColor === currentColor) {button.classList.add(selectedClassName);
      }

      // …and register a listener for when that button is clicked
      button.addEventListener("click", handleButtonClick);
      page.appendChild(button);
    }
  });
}

// Initialize the page by constructing the color options
constructOptions(presetButtonColors);

提供四种色彩选项,而后在选项页上生成带有 onclick 事件侦听器的按钮。当用户单击按钮时,它会更新扩大存储中的色彩值。因为扩大的所有文件都从该存储中提取色彩信息,因而不须要更新其它值。

下一步

恭喜!这个目录当初领有一个性能残缺的 Chrome 扩大,只管它过于简略。

下一步呢?

  • Chrome Extension Overview 提供了一些反对,并填充了很多对于扩大架构的细节,以及一些开发人员心愿相熟的特定概念。
  • 在 debugging tutorial 中理解可用于调试扩大的选项。
  • Chrome 扩大能够拜访弱小的 API,而不仅仅是凋谢 web 上的 API。chrome.*API 文档介绍了所有的 API。
  • developer’s guide 中有几十个对于创立高级扩大的相干文档附加链接。

参考资料

  • Chrome Extensions : Getting started
正文完
 0