WebExt Bridge 实战

Web3Hacker.World 是一个集合程序员黑客、对新事物好奇的种子用户、及 vc 投资者组合的围绕 万物皆可 Web3 的理念打造的生态体系。
我们将持续分享 Web3 的最新技术发展,并打造一个开放式的黑客社区并产出真正非庞氏的 Web3 产品

本文是我们在开发 Web3 的 RWA 钱包过程中,研究 webext-bridge 整理的浏览器扩展的不同模块之间传递消息的逻辑时整理的,最终我们会有两个开源项目产出:

本文介绍 WebExt Bridge 的使用。

WebExt Bridge 使得你在开发浏览器扩展时,有更加统一简便的消息传输逻辑。

TL;DR

  • content-script <=> background, popup, option
// content-script
const yourJsonDataToPass = { what: 'ever json you want to pass here' }
await sendMessage('eventNameA', yourJsonDataToPass, 'background')
onMessage('eventNameB', async (msg) => { console.log(msg) })

// background or popup

// currentTabId only can get in background script, so you should store it in storage so in popup we can get the tabId
const currentTabId = ref('')
browser.tabs.onActivated.addListener(async ({ tabId }) => {
  currentTabId.value = tabId
})
onMessage('eventNameA', async (msg) => { console.log(msg) })
await sendMessage('eventNameB', yourJsonDataToPass, `content-script@${tabId}`)
  • 除了 content-script 之外,其他各方互相发送接收消息都比较简单,不需要附带 tabId

初始设置

我准备了一个 demo 代码,在 webext-bridge 分支,方便大家可以快速尝试。

git clone --depth=1 git@github.com:Web3HackerWorld/vitesse-webext-tutorial.git --branch webext-bridge 
cd vitesse-webext-tutorial
pnpm i
pnpm dev

pnpm dev 命令使用 run-p 同时运行多个 dev: 开头的 scripts,其中 dev:html 是自动帮你打开一个本地网页,以便你直接查看浏览器扩展的效果。

打开页面后,并不会出现我们的 Vitesse webext tutorial 浏览器扩展,需要你打开 chrome://extensions/,点击 Load unpacked,然后定位到本代码的 extensions 目录即可。

注意在修改 manifest.ts 文件后,需要你手动删除扩展再重新点击 Load unpacked 按钮加载,其他代码的修改可以通过安装 [Extensions Reloader](https://chrome.google.com/webstore/detail/extensions-reloader/fimgfedafeadlieiabdeeaodndnlbhid) 来方便你点击按钮即可刷新扩展,当然你可以可以直接打开 chrome://extensions/,点击你的扩展的右下角的 reload 按钮。

1. content-script <=> background

content-script => background

1.在 content-script (/src/contentScripts/views/App.vue) 定义 content-scipt=>background 发送按钮的代码

<button @click="doContentScriptToBackground">
  content-scipt=>background
</button>
import { sendMessage } from 'webext-bridge/content-script'

const clickCount = ref(1)
const doContentScriptToBackground = async () => {
  await sendMessage('content-scipt=>background', {
    count: clickCount.value,
  }, 'background')
  clickCount.value++
}

2.在 background (/src/background/main.ts) 定义消息的接收函数

onMessage('content-scipt=>background', async (msg) => {
  console.log('====> msg :', msg)
  const keys = Object.keys(msg)
  const { sender, data } = msg
  console.log('====> keys, sender, data :', keys, sender, data)
})

3.打开你的扩展的 service worker (打开 chrome://extensions/,找到 Vitesse WebExt Tutorial 扩展,有个 Inspect views service worker 按钮,点击后会弹出
[图片上传失败...(image-27fec9-1685625077879)]

4.点击网页上被扩展注入的 content-scipt=>background 按钮,会看到 service worker 里出现类似这样的 log。

[图片上传失败...(image-72e9ab-1685625043619)]

[图片上传失败...(image-b94648-1685625043619)]

content-script <= background

此时,我们可以在 background 收到 content-scipt=>background 消息时触发 content-script<=background 事件。

1.在 App.vue(/src/contentScripts/views/App.vue)添加如下代码,定义 content-scipt<=background 事件。

onMessage('content-scipt<=background', async (msg) => {
  // eslint-disable-next-line no-console
  console.log('====> content-scipt<=background msg :', msg)
  return { cool: 'Got you! I am cool from content-script' }
})

2.在 background (/src/background/main.ts) 的 content-scipt=>background 事件回调函数定义发送消息给 content-scipt<=background 的代码,这里我们取巧了下,在网页界面上点击触发事件 background 收到后,立即又触发一个新的事件给前端的 content-script, 完整代码如下:

onMessage('content-scipt=>background', async (msg) => {
  // eslint-disable-next-line no-console
  console.log('====> msg :', msg)
  const keys = Object.keys(msg)
  const { sender, data } = msg
  // eslint-disable-next-line no-console
  console.log('====> keys, sender, data :', keys, sender, data)

  const rz = await sendMessage('content-scipt<=background', {
    time: new Date(),
  }, `content-script@${currentTabId}`)
  // eslint-disable-next-line no-console
  console.log('====> response from content-sciript', rz)

  return { yaha: 'hoho' }
})

我们在这里也添加了返回数据给前面的 sendMessage 了,这样我们也一并改造下前面的 doContentScriptToBackground 函数

const doContentScriptToBackground = async () => {
  const rz = await sendMessage('content-scipt=>background', {
    count: clickCount.value,
  }, 'background')
  clickCount.value++
  // eslint-disable-next-line no-console

  console.log('====> doContentScriptToBackground sendMessage rz :', rz)
}

点击下扩展的 reload 按钮,重载下扩展以便触发 service worker 刷新,然后刷新下网页 http://localhost:5173/,可能还需要切换到别的 tab 再切回来下,因为我们需要在 background 获得当前激活的 tabId

let currentTabId = 0
// communication example: send previous tab title from background page
// see shim.d.ts for type declaration
browser.tabs.onActivated.addListener(async ({ tabId }) => {
  currentTabId = tabId
})

3.最后可以点击网页上的按钮,再次触发 content-scipt=>background 事件了,background 收到这个事件后,也触发了新的 content-scipt<=background 事件给网页的 contentScripts

[图片上传失败...(image-fe16ce-1685625043619)]

content-script <=> popup

1.在 content-script (/src/contentScripts/views/App.vue) 定义 content-scipt=>popup 发送按钮的代码以及 content-scipt<=popup 接收消息的事件代码。

<br>
<br>
<button @click="doContentScriptToPopup">
  content-scipt=>popup
</button>
const doContentScriptToPopup = async () => {
  const rz = await sendMessage('content-scipt=>popup', {
    count: clickCount.value,
  }, 'popup')
  clickCount.value++
  // eslint-disable-next-line no-console
  console.log('====> doContentScriptToPopup sendMessage rz :', rz)
}

onMessage('content-scipt<=popup', async (msg) => {
  // eslint-disable-next-line no-console
  console.log('====> content-scipt<=popup msg :', msg)
  return { cool: 'Got you popup! I am cool from content-script' }
})

2.在 popup (/src/popup/views/popup.vue)定义事件 content-scipt=>popup 以及 sendMessageToContentScript 按钮,这样我们在 popup 里面点击按钮可以触发逻辑来给 contentScript 发消息。我们定义了 currentTabIdstorage 里面,这样我们在 popup 里才能获得当前激活的 tabId,这样才有办法往该 tabIdcontent-script 发送消息。

import { currentTabId } from '~/logic/storage'

const count = ref(0)
onMessage('content-scipt=>popup', async (msg) => {
  // eslint-disable-next-line no-console
  console.log('====> content-scipt=>popup msg :', msg)
  count.value = msg.data.count
  return { cool: 'Got you! I am cool from popup' }
})

const sendMessageToContentScript = async () => {
  console.log('====> currentTabId.value :', currentTabId.value)
  const rz = await sendMessage('content-scipt<=popup', {
    time: new Date(),
  }, `content-script@${currentTabId.value}`)
  // eslint-disable-next-line no-console
  console.log('====> response from content-sciript', rz)
}
currentTabId {{ currentTabId }} <br >
count from content-script: {{ count }}
<button class="mt-2 btn" @click="sendMessageToContentScript">
  content-scipt&lt;= popup
</button>

3.现在可以右键点击浏览器扩展图标,点击弹出的菜单最底部的菜单项 Inspect Popup, 然后点击左侧的 content-scipt=>popup,可以看到 content-scriptpopup 发送的消息了,并且 popup 里的事件接收回调还返回了 { cool: 'Got you! I am cool from popup' }content-script。注意,这里只有打开了 popup 弹出,才有成功注册 content-scipt=>popup 事件监听,如果还未打开 popup 弹窗就在页面上点击 content-scipt=>popup 会报错的。因为 popup 的代码压根没有运行。所有这种场景估计实际开发中是用的比较少。

4.再点击 popup 里的 content-scipt<=popup 按钮,则可以看到 content-scriptcontent-scipt<=popup 事件监听回调触发,并返回 { cool: 'Got you popup! I am cool from content-script' } 给了popup

popup <=> background

1.在 background 里添加事件监听以及发送代码

onMessage('background<=popup', async (msg) => {
  // eslint-disable-next-line no-console
  console.log('====> msg :', msg)
  const keys = Object.keys(msg)
  const { sender, data } = msg
  // eslint-disable-next-line no-console
  console.log('====> keys, sender, data :', keys, sender, data)

  const rz = await sendMessage('background=>popup', {
    time: new Date(),
  }, 'popup')
  // eslint-disable-next-line no-console
  console.log('====> response from popup', rz)

  return { yoho: 'huhu' }
})

2.在 popup 里添加事件监听以及发送代码

onMessage('background=>popup', async (msg) => {
  // eslint-disable-next-line no-console
  console.log('====> background=>popup msg :', msg)
  count.value = msg.data.count
  return { cool: 'Got you! I am cool from popup' }
})

const sendMessageToBackground = async () => {
  const rz = await sendMessage('background<=popup', {
    time: new Date(),
  }, 'background')
  // eslint-disable-next-line no-console
  console.log('====> response from background', rz)
}
<br>
<br>
<button class="mt-2 btn" @click="sendMessageToBackground">
  background&lt;= popup
</button>

3.如图,打开 service worker 的 console (右侧下方) 以及 popup 的 console(右侧上方)

我是来自 Web3Hacker.World的 Bruce,22 年 5 月 All In Web3,后面连续参加了 10 多个黑客松并三个月内拿到 15 个左右的赛道奖及 Grants,累积产值 70 万 RMB 左右(含后续参与其他团队获得)。
后面又经历休息、搬家到海边(懒散了几个月)、从新学习了大量新技术。现在又开始新的一轮的 Web3 掘金。
这波主要围绕我创建的 BuidlerProtocol 打造 万物皆可 Web3 的跨链的 Web3 App Store 生态平台来制作各种不同的实际应用场景的 DApp 参加各种不同的黑客松比赛并尝试获得 Web3 投资机构的投资。
在这个过程中,我会用 Web3 的技术开发一系列产品,并在过程中实际使用他们。比如使用 Web3 的博客平台来分享我们后续的付费阅读的文章 Web3NFT.Social.


往期回顾

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 220,492评论 6 513
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 94,048评论 3 396
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 166,927评论 0 358
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 59,293评论 1 295
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 68,309评论 6 397
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 52,024评论 1 308
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,638评论 3 420
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 39,546评论 0 276
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 46,073评论 1 319
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 38,188评论 3 340
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 40,321评论 1 352
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,998评论 5 347
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,678评论 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 32,186评论 0 23
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 33,303评论 1 272
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 48,663评论 3 375
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 45,330评论 2 358

推荐阅读更多精彩内容