Axios 未在background.js 中定义(manifest v3)

发布于 2025-01-15 01:44:45 字数 380 浏览 4 评论 0原文

我目前正在开发 chrome 扩展。

我想要的工作流程:content-script.js 向 background.js 发送一条消息。一旦后台使用 eventListener 接收到消息,后台就会开始执行一个进程,其中包括 axios.post 请求以及 localStorage.setItem。由于我已将项目的清单迁移到 V3,background.js 成为了服务工作者。因此,在执行扩展时,background.js 控制台会显示“axios 未定义”以及“localStorage 未定义”。 因此我需要一种在background.js(manifest v3)中使用它的方法。

注意:我也尝试使用 chrome.storage.local,但 set 函数的回调被调用,但 get 函数没有获取任何值。

I am currently working on a chrome Extension.

My desired workflow : content-script.js sends a message to background.js. Once the message is received by background using eventListener, background starts executing a process which includes an axios.post request as well as localStorage.setItem. Since I have migrated the project's manifest to V3, background.js becomes a service worker. Hence while executing the extension, the background.js console says that "axios is not defined" as well as "localStorage is not defined".
Hence I need a way to use this in background.js (manifest v3).

Note : I also tried using chrome.storage.local, but the set function's callback is getting called, but the get function doesn't get any value.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

红颜悴 2025-01-22 01:44:45

不要忘记将“存储”权限放入清单文件中。

ma​​nifest.json (v3)

{
  "name": "Test extenstion",
  "description": "Test Extension!",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "action": {},
  "permissions": ["storage", "activeTab", "scripting"]
}

Background.js

chrome.storage.sync.set({key: value}, function() {
  console.log('Value is set to ' + value);
});

chrome.storage.sync.get(['key'], function(result) {
  console.log('Value currently is ' + result.key);
});

来源:
https://developer.chrome.com/docs/extensions/reference/storage /#用法

Do not forget to place the "storage" permission in the manifest file.

manifest.json (v3)

{
  "name": "Test extenstion",
  "description": "Test Extension!",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "action": {},
  "permissions": ["storage", "activeTab", "scripting"]
}

Background.js

chrome.storage.sync.set({key: value}, function() {
  console.log('Value is set to ' + value);
});

chrome.storage.sync.get(['key'], function(result) {
  console.log('Value currently is ' + result.key);
});

Source:
https://developer.chrome.com/docs/extensions/reference/storage/#usage

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文