5 了解 Chrome 扩展通信 |作者:M2K Developments – Freedium

预览图像

5 了解 Chrome 扩展程序通信

我们的浏览器扩展中的数据流是创建任何令人难以置信且有用的工具的重要组成部分。在本文中,我们希望展示......

M2K 发展

M2K 发展

A11Y-LIGHT 系列 · 2024 年 9 月 5 日(更新时间:2024 年 11 月 17 日) · 免费:是

我们的浏览器扩展中的数据流是创建任何令人难以置信且有用的工具的重要组成部分。在本文中,我们希望向您展示数据如何在扩展的不同部分内移动。

到目前为止,在我们之前写的文章中,我们已经介绍了 chrome 扩展有 3 个主要部分。弹出窗口、内容脚本和背景脚本。所有这些部分都可以独立工作,此外,您可以只使用其中之一即可拥有一个功能齐全的 chrome 扩展。

没有

后台脚本:这些是在后台全局运行的 JavaScript 文件,独立于任何打开的网页。

为了与扩展的不同部分进行通信,我们将使用 chrome.runtime API 和/或 chrome.tabs.sendMessage

该 API 检索 Service Worker,返回有关清单的详细信息,并侦听和响应扩展生命周期中的事件。您还可以使用此 API 将 URL 的相对路径转换为完全限定的 URL(我们将在 Web 可访问性的文章中介绍这一点)。此 API 不需要权限(我们将在下一篇文章中介绍权限)。chrome.runtime

至于 API,将在以后的文章中详细介绍它,但目前有 2 个主要函数/方法将用于通信,并且chrome.tabschrome.tabs.querychrome.tabs.sendMessage

设置示例 Chrome 扩展项目

如果您已经有一个 chrome 扩展项目,那就太好了!如果没有,请创建一个文件夹/director 并在其中包含以下文件;

  • index.html
  • styles.css
  • scripts.js
  • background.js
  • content.js
  • manifest.json

index.html,将分别用于扩展弹出窗口的 UI 和功能。并将分别用作内容脚本和背景脚本。styles.cssscripts.jscontent.jsbackground.js

扩展详细信息 — Manifest.json

您会注意到有一个新字段 . 我们将在下一篇文章中详细介绍这一点,但简而言之,它只是告诉 chrome 浏览器该扩展将使用来自 chrome.tabs API 和 的函数来获取选项卡信息并将数据发送到运行内容脚本的那些选项卡。permissionschrome.tabs.querychrome.tabs.sendMessage

注: 您不能使用chrome.runtime.sendMessage

{
    "name": "Web Color Changer",
    "short_name": "Web Color Changer",
    "version": "1.0.0.0",
    "description": "Change the background color of any website",
    "manifest_version": 3,
    "permissions": [
        "tabs"
    ],
    "action": {
        "default_popup": "index.html",
        "default_title": "Web Color Changer Popup"
    },
    "background": {
        "service_worker": "background.js",
        "type": "module"
    },
    "content_scripts": [
        {
            "matches": [
                ""
            ],
            "js": [
                "content.js"
            ]
        }
    ]
}

扩展弹出窗口 UI — index.html 和 styles.css


    Hello World

    

Web Color Changer

body { width: 200px; height: 300px; display: flex; flex-direction: column; justify-content: center; background: linear-gradient(#ffffff, #ded4e0); color: #9703c4; margin: 0 auto; text-align: center; padding: 0px 30px; } input { width: 100%; } button { margin: 10px; background: #47015c; padding: 10px 0px; border: none; border-radius: 10px; box-shadow: rgba(0, 0, 0, 0.35) 0px 5px 15px; color: white; font-weight: 700; cursor: pointer; transition: 0.4s all; } button:hover { background: #9703c4; border-radius: 30px; box-shadow: rgb(38, 57, 77) 0px 20px 30px -10px; }

在本地安装扩展时,它应如下所示。

没有

弹出窗口功能 — Scripts.js

现在我们要对弹出窗口的功能进行编码。这个想法是,扩展应该自动检测当前网页的背景颜色并相应地更改输入颜色。此外,当用户单击“更改颜色”按钮时,它应该将网站的背景颜色更改为输入颜色选择的颜色。

这就是 chrome.runtime API 的用武之地。该 API 有两个主要的功能/方法,用于手线应用内通信

chrome.runtime.sendMessage(data_you_want_send)

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {})

两者都是 Google 的官方文档 此处.分别是发送者和侦听者。

// get active tab
chrome.tabs.query({ active: true }, (tabs) => {
    if (tabs[0].url) {
        //send to content scripts to get the color
        chrome.tabs.sendMessage(tabs[0].id, { action: "get-color" });
    }
});

// listen for message coming from background script (background.js) or content script (content.js)
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {

    // change the color of the input to make the website as a default
    if (request.action === "web-color") {
        const color = request.color;
        const inputcolor = document.querySelector('input');
        if (color.includes("#")) {
            inputcolor.value = color;
        } else {
            // convert rgb e.g rgb(216, 19, 19) to #d81313
            // const values = color
            //     .replace("(", "")
            //     .replace(")", "")
            //     .replace("rgb", "")
            //     .split(",")
            // const [r, g, b] = values;
        }
    }
});

// send color to the content scripts
document.querySelector('button').onclick = () => {
    const inputcolor = document.querySelector('input');
    const color = inputcolor.value;

    // you can send numbers, strings, arrays, and objects
    // send background scripts background.js
    chrome.runtime.sendMessage({ action: "change-color", color: color });

    // get active tab
    chrome.tabs.query({ active: true }, (tabs) => {
        if (tabs[0].url) {
            //send message to content scripts to change color
            chrome.tabs.sendMessage(tabs[0].id, { action: "change-color", color: color })
        }
    });
}

如果你想在 React JS 中实现相同的作,例如,你可以在你的文件中做这样的事情。App.jsx

/* eslint-disable no-unused-vars */
/*global chrome*/

import { useEffect, useState } from 'react'

function App() {

  const [color, setColor] = useState("#000000");

  useEffect(() => {

    // get active tab
    chrome.tabs.query({ active: true }, (tabs) => {
      if (tabs[0].url) {
        //send to content scripts to get the color
        chrome.tabs.sendMessage(tabs[0].id, { action: "get-color" });
      }
    });

    const listener = (request, sender, sendResponse) => {
      // change the color of the input to make the website as a default
      if (request.action === "web-color") {
        const color = request.color;
        const inputcolor = document.querySelector('input');
        if (color.includes("#")) {
          setColor(color);
        } else {
          // convert rgb e.g rgb(216, 19, 19) to #d81313
          // const values = color
          //     .replace("(", "")
          //     .replace(")", "")
          //     .replace("rgb", "")
          //     .split(",")
          // const [r, g, b] = values;
        }
      }
    };
    chrome.runtime.onMessage.addListener(listener);
    return () => chrome.runtime.onMessage.removeListener(listener);
  }, []);

  const onChangeColor = () => {
    const inputcolor = document.querySelector('input');
    const color = inputcolor.value;

    // you can send numbers, strings, arrays, and objects
    // send background scripts background.js
    chrome.runtime.sendMessage({ action: "change-color", color: color });

    // get active tab
    chrome.tabs.query({ active: true }, (tabs) => {
      if (tabs[0].url) {
        //send to content scripts
        chrome.tabs.sendMessage(tabs[0].id, { action: "change-color", color: color })
      }
    });
  }

  return (

      

Web Color Changer

setColor(e.target.value)} type="color" /> </> ) } export default App

更改网站颜色 — 内容脚本content.js

这是网站背景颜色发生变化的地方。内容脚本侦听来自弹出窗口或后台脚本的消息,并在执行作后发回消息。

// listening for messages from background script or popup 
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {

    // listening for message from the scripts.js (Popup) to get the color
    if (request.action == "get-color") {
        const color = document.body.style.background;

        // sending the color to the popup and background.js (It sends to both)
        chrome.runtime.sendMessage({ action: "web-color", color: color })
    }

    // listening for message from the Popup (scripts.js) to change color
    else if (request.action == "change-color") {
        const color = request.color;
        document.body.style.background = color;

    }

});

当内容脚本发送消息时,弹出窗口和后台脚本会同时接收数据。如果弹出窗口未打开,则只有后台脚本将接收消息。

后台脚本 background.js

对于此扩展,我们只记录在后台脚本中发送的消息background.js

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {

    // listening for message from the scripts.js (Popup) to get the color
    if (request.action == "get-color") {

        // send to all content scripts
        chrome.runtime.sendMessage({ action: "get-color" });
    }
});

Web 颜色转换器扩展

如果您已经走到这一步,那么我们就完成了!您拥有一个了不起的、令人难以置信的、令人敬畏的、奇妙的、改变游戏规则的背景变色器 chrome 浏览器扩展。根据自己的喜好更改任何网站的颜色。

没有

没有

照片由 罗曼·辛克维奇 on Unsplash

你可以在这里找到普通 HTML、CSS 和 JavaScript 实现的源代码,或者在这里找到 React JS 的源代码

额外提示

Chrome 扩展能够与其他 chrome 扩展进行通信。

暂无评论

发送评论 编辑评论


				
|´・ω・)ノ
ヾ(≧∇≦*)ゝ
(☆ω☆)
(╯‵□′)╯︵┴─┴
 ̄﹃ ̄
(/ω\)
∠( ᐛ 」∠)_
(๑•̀ㅁ•́ฅ)
→_→
୧(๑•̀⌄•́๑)૭
٩(ˊᗜˋ*)و
(ノ°ο°)ノ
(´இ皿இ`)
⌇●﹏●⌇
(ฅ´ω`ฅ)
(╯°A°)╯︵○○○
φ( ̄∇ ̄o)
ヾ(´・ ・`。)ノ"
( ง ᵒ̌皿ᵒ̌)ง⁼³₌₃
(ó﹏ò。)
Σ(っ °Д °;)っ
( ,,´・ω・)ノ"(´っω・`。)
╮(╯▽╰)╭
o(*////▽////*)q
>﹏<
( ๑´•ω•) "(ㆆᴗㆆ)
😂
😀
😅
😊
🙂
🙃
😌
😍
😘
😜
😝
😏
😒
🙄
😳
😡
😔
😫
😱
😭
💩
👻
🙌
🖕
👍
👫
👬
👭
🌚
🌝
🙈
💊
😶
🙏
🍦
🍉
😣
Source: github.com/k4yt3x/flowerhd
颜文字
Emoji
小恐龙
花!
上一篇
下一篇