0

0

0

修罗

站点介绍

只有了解事实才能获得真正的自由

chrome插件开发 - 入门

修罗 2021-11-21 1760 1条评论 JS

首页 / 正文

目录

chrome插件开发 - 入门

官方文档:https://developer.chrome.com/docs/extensions/mv3/getstarted/(需要vpn)

1637485873428.png

插件中主要包含 background scripts(插件常驻进程), content scripts(注入网页的脚本), an options page(操作页面), UI elements(插件ui界面) 和许多逻辑代码。

扩展程序使用HTML, CSS, and JavaScript来开发。

1、清单文件

新件Helloworld文件夹,创建清单文件

1637486256643.png

manifest.json

{
  "name": "HelloWorld",
  "description": "Build an Extension!",
  "version": "1.0",
  "manifest_version": 3
}

进入扩展程序界面,打开开发者模式,加载我们编写的Helloworld文件夹。

1637486717564.png

加载完毕

1637486752414.png

2、background script

编写程序:扩展加载后给缓存中存储一个color变量。

需要在清单文件中注册,并指定脚本文件路径:

2.1 manifest.json添加background

{
  "name": "HelloWorld",
  "description": "Build an Extension!",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  }
}

2.2 新建background.js

let color = '#3aa757';

// 插件首次安装调用
chrome.runtime.onInstalled.addListener(() => {
  // set a value using the [storage] API 
  chrome.storage.sync.set({ color });
  console.log('Default background color set to %cgreen', `color: ${color}`);
});

重载报错

1637488098795.png

2.3 清单文件中设置权限

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

点击service worker打开开发工具

1637488215030.png

3、用户界面

3.1 点击程序图标弹出界面

在清单文件中添加一个action对象,设置popup.html为默认弹出界面。

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

新建popup.html

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

button.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;
}

点击扩展程序图标,弹出按钮

1637491256328.png

3.2 action逻辑

popup.html载入js脚本

<script src="popup.js"></script>

popup.js

初始化按钮颜色,按钮点击页面对背景颜色修改

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

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

// 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;
  });
}

需要 activeTab 权限允许程序临时访问当前页面, scripting 权限使用 executeScript 方法.

{
  "name": "HelloWorld",
  "description": "Build an Extension!",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["storage", "activeTab", "scripting"],
  "action": {
    "default_popup": "popup.html"
  }
}

效果:点击白色按钮网页背景变色

1637493078769.png

3.2 在action添加图标

图标下载地址:https://storage.googleapis.com/web-dev-uploads/file/WlD8wC6g8khYWPJUsQceQkhXSlv1/wy3lvPQdeJn4iqHmI0Rp.zip

1637491400233.png

显示效果

1637491431610.png

{
  "name": "HelloWorld",
  "description": "Build an Extension!",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["storage", "activeTab", "scripting"],
  "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"
    }
  }
}

3.3 清单添加icon

1637491480247.png

效果

1637491527159.png

注意:

只能在网站中注入content scripts,不能在浏览器内部页面,如扩展程序页面中注入脚本。
官网原文
Extensions can not inject content scripts on internal Chrome pages like "chrome://extensions". Be sure to try out the extension on a real webpage like https://google.com.

4、users options

4.1 配置选项跳转页面

1637492420614.png

4.2 程序设计

选项跳转

1637493187554.png

跳转到此页面,在此页面切换颜色

1637493230876.png

返回可以切换背景颜色

1637493307922.png

4.3 程序实现

1、manifest.json

{
  "name": "HelloWorld",
  "description": "Build an Extension!",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["storage", "activeTab", "scripting"],
  "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"
  },
  "options_page": "options.html"
}

2、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>

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);

评论(1)

  1. TonaldOxiva 游客 2024-03-27 00:51 回复

    Купить детские площадки в Кривом Роге можно без особых проблем.Универсальность тренажеров для улицы обусловлена тем, что человек работает исключительно с весом собственного тела, снижая нагрузки на суставы.
    http://mixedarts.ru/013.html
    http://mfk-lokomotiv.com.ua/news_arh.php?year=2016
    http://fcmetalurg.com/season/metalurg-2/allmatches2/

    До того ж на всі вироби виробник надає гарантійне обслуговування на протязі одного року.Игровой комплекс Сказка 12 из дерева уличный.


最新评论

  • https://www.studyglobus.com/author/carroll34a5552/

    Ценники на вывоз мусора сейчас космос, любые лайфхаки по экономии в тему.

  • Richardgrold

    1xbet onlayn kazino platforması ilə vaxtınızı daha səmərəli və maraqlı keçirin. Saytın canlı kazino bölməsi istifadəçilərə fərqli bir dünya təklif edir. Burada canlı dilerli kazino oyunlarının hər bir növünü sınaqdan keçirə bilərsiniz. Krupyelərin peşəkarlığı oyunun dinamikasını və marağını artırır. Müntəzəm olaraq yenilənən oyun siyahısı cansıxıcılığa yol vermir. Hesabınızı artırmaq üçün onlarla fərqli və etibarlı üsul mövcuddur. Qazanılan pullar cəmi bir neçə dəqiqə ərzində şəxsi hesabınıza köçürülür. Aktiv fəaliyyətinizə görə fərdi bonuslar və hədiyyələr qazana bilərsiniz. Dəstək xidməti həm çat, həm də e-poçt vasitəsilə kömək göstərir. 1xbet ailəsinə qoşulun və böyük uduşlar üçün ilk addımı atın. onlayn kazino

  • 砂岩白丘

    我一直梦想, 看到你们相册那样的地方。真棒。

  • 城市地標

    我喜欢, 这里分享真实经验。你的项目 就是 属于这里的。请继续。

  • 宗教地標

    我热爱这样的想法, 去那么多国家。真的很鼓舞。

  • 觀景高地

    能感受到热爱。继续保持 感受。

  • 最佳季節

    我关注这样的资源, 写得很实在。你的网站 就是 属于这里的。加油。

  • 1

    1

  • 1

    1

  • -1' OR 2+158-158-1=0+0+0+1 or 'TKCTZnRa'='

    1

日历

2026年07月

   1234
567891011
12131415161718
19202122232425
262728293031 

文章目录

推荐关键字: Linux webpack js 算法 MongoDB laravel JAVA jquery javase redis