Quasar CLI with Vite - @quasar/app-vite
后台脚本运行在 BEX 自身的上下文中,可以监听所有可用的浏览器扩展事件。
WARNING
在 Chrome 中使用 Manifest v3 时,后台脚本实际上是一个 Service Worker。目前 Firefox 的 Manifest v3 尚未采用这一机制。
注册后台脚本
/src-bex/manifest.json 是定义 BEX 的核心文件,后台脚本也在这里定义:
"chrome": {
"background": {
"service_worker": "background.js"
}
},
"firefox": {
"background": {
"scripts": [ "background.js" ]
}
}content_paste
给 TS 开发者
后台脚本和内容脚本使用 .ts 扩展名。在 manifest.json 文件中也请使用该扩展名!例如:“background.ts”、“my-content-script.ts”。虽然浏览器厂商只支持 .js 扩展名,但 Quasar CLI 会自动转换文件扩展名。
案例分析
假设我们想监听浏览器中新标签页的打开事件,然后在 Quasar 应用中做出响应。首先,我们需要监听新标签页打开的事件,并发送一个事件通知 Quasar 应用:
/**
* Importing the file below initializes the extension background.
*
* Warnings:
* 1. Do NOT remove the import statement below. It is required for the extension to work.
* If you don't need createBridge(), leave it as "import '#q-app/bex/background'".
* 2. Do NOT import this file in multiple background scripts. Only in one!
* 3. Import it in your background service worker (if available for your target browser).
*/
import { createBridge } from "#q-app/bex/background";
const bridge = createBridge({ debug: false });
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
bridge.send("bex.tab.opened", { url: tab.url });
});content_paste
然后在 Quasar 应用中,通过组件的生命周期钩子来监听这个事件:
import { useQuasar } from "quasar";
import { onBeforeUnmount } from "vue";
export default {
setup() {
const $q = useQuasar();
// 接收后台脚本发送的 URL 的函数
function doOnTabOpened(url) {
console.log("New Browser Tab Openend: ", url);
}
// 添加监听器
$q.bex.on("bex.tab.opened", doOnTabOpened);
// 别忘了清理
onBeforeUnmount(() => {
$q.bex.off("bex.tab.opened", doOnTabOpened);
});
return {};
},
};content_paste
浏览器扩展的后台脚本有各种各样的可用事件。如果您想在这方面深入探索,善用搜索引擎会很有帮助。