我在使用清单 v3 时尝试进行 chrome 扩展并出现 Getting localStorage undefined 错误

I was trying to make a chrome extension and Getting localStorage undefined error while using manifest v3

清单 v2 工作正常。但是使用 manifest v3 我收到错误“ReferenceError: localStorage is not defined”

manifest.json

{
  "name": "Getting Started Example",
  "description": "Build an Extension!",
  "version": "1.0",
  "manifest_version": 3,
  "background": {
    "service_worker": "background.js"
  },
  "permissions": ["storage", "activeTab", "contextMenus"],
  "action": {
    "default_popup": "popup.html"
  }
}

background.js

var contextMenuItems = {
  "title": 'Add to notepad"',
  "contexts": ["selection"],
  "id": "myContextMenuId"
};
chrome.contextMenus.create(contextMenuItems);
chrome.contextMenus.onClicked.addListener(function(clickData){
  if(clickData.menuItemId == "myContextMenuId" && clickData.selectionText){
   localStorage.setItem("text", "clickData.selectionText");
  }
});

ManifestV3 中的后台脚本现在是 service worker,因此它无法访问仅在 window 上公开的内容,例如 HTML5 localStorage 或 DOM。顺便说一句,service workers 没有 window,他们的全局上下文是 selfglobalThis.

解决方案是切换到 chrome.storage.local. It's an entirely different storage available in all extension contexts including content scripts. Note that a) it's asynchronous so the usage is different and b) it doesn't currently return a Promise due to a bug in Chrome,这样您就不能 await 它了。在修复之前,请使用文档中显示的回调版本。

存储:

chrome.contextMenus.onClicked.addListener(info => {
  if (info.menuItemId == 'myContextMenuId' && info.selectionText) {
    chrome.storage.local.set({text: info.selectionText});
  }
});

正在弹出窗口中阅读:

chrome.storage.local.get('text', ({text}) => {
  // the callback runs asynchronously so you should use the value here
  document.body.prepend(text);
});