浏览器扩展 - 如何在 background.js 文件中包含第三方库

Browser extension - how to include third part library inside background.js file

如何在不使用 webpack 的 chrome 扩展中包含 npm 库?我想在我的 background.js 文件中调用一个库,但如果我在清单后台脚本部分中声明该库,它将无法用于后台脚本并记录此错误:background.js:8 Uncaught ReferenceError: lamejs is not defined

有什么帮助吗?

manifest.json

{
  "manifest_version": 2,
  "name": "test extension",
  "description": "test",
  "permissions": [
    "https://*",
    "webRequest",
    "activeTab",
    "downloads"
  ],
  "background": {
    "scripts": [
      "js/background.js",
      "js/lame.min.js"
    ],
    "persistent": true
  },
  "browser_action": {
    
  },
  "version": "1.0.0",
  "content_security_policy": "script-src 'self' 'unsafe-eval'; object-src 'self'"
}

background.js

const mp3encoder = new lamejs.Mp3Encoder(1, 44100, 128);
// other code here

请记住,脚本是线性加载的。这意味着加载脚本的顺序非常重要。始终将 background.js 放在该数组的末尾。这部分代码 const mp3encoder = new lamejs.Mp3Encoder(1, 44100, 128) 在您使用时不可用,因为您在 background.js 加载后加载 lamejs

这是您的代码:

"background": {
    "scripts": [
      "js/background.js",
      "js/lame.min.js"
    ],

改为这样做:

"background": {
    "scripts": [
      "js/lame.min.js",
      "js/background.js"
    ],