为什么捐赠
API 浏览器
联系站长
Quasar CLI with Vite - @quasar/app-vite
内容脚本

内容脚本运行在网页的上下文中。每个运行扩展的标签页都会有一个新的内容脚本实例。

通信 / 事件

BEX 各部分(后台脚本、内容脚本和 devtools/popup/options 页面)之间的通信通过 BEX Bridge 实现。

注册内容脚本

/src-bex/manifest.json 是定义 BEX 的核心文件。在这里您也可以定义内容脚本:

/src-bex/manifest.json

"content_scripts": [
  {
    "matches": [ "<all_urls>" ],
    "css": [ "assets/content.css" ],
    "js": [ "my-content-script.ts" ]
  }
]

针对 TS 开发者

您的后台脚本和内容脚本使用 .ts 扩展名。在 manifest.json 文件中也请使用该扩展名!例如:“background.ts”、“my-content-script.ts”。虽然浏览器厂商只支持 .js 扩展名,但 Quasar CLI 会自动转换文件扩展名。

案例分析

假设我们想在 Quasar 应用中响应按钮点击事件,并高亮底层网页上的某些文本,可以通过内容脚本实现:

Quasar App, /src

setup () {
  const $q = useQuasar()

  async function myButtonClickHandler () {
    await $q.bex.send('highlight.content', { selector: '.some-class' })
    $q.notify('Text has been highlighted')
  }

  return { myButtonClickHandler }
}
/src-bex/assets/content.css

.bex-highlight {
  background-color: red;
}
/src-bex/my-content-script.js:

/**
 * Importing the file below initializes the content script.
 *
 * Warning:
 *   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/content'".
 */
import { createBridge } from "#q-app/bex/content";

// The use of the bridge is optional.
const bridge = createBridge({ debug: false });

bridge.on("highlight.content", ({ payload }) => {
  const el = document.querySelector(data.selector);
  if (el !== null) {
    el.classList.add("bex-highlight");
  }
});

bridge
  .connectToBackground()
  .then(() => {
    console.log("Connected to background");
  })
  .catch((err) => {
    console.error("Failed to connect to background:", err);
  });

内容脚本存在于一个独立的世界中,允许内容脚本对其 JavaScript 环境进行更改,而不会与页面或其他内容脚本发生冲突。

独立的世界不允许内容脚本、扩展和 Web 页面访问其他人创建的任何变量或函数。这也使内容脚本能够启用网页不应该访问的功能。