我试图制作一个 chrome 扩展,并在使用清单 v3 时出现“获取 localStorage 未定义”错误

Dee*_*Kay 3 google-chrome-extension google-chrome-devtools manifest.json

使用清单 v2 可以正常工作。但对于清单 v3,我收到错误“ReferenceError:localStorage 未定义”

清单.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"
  }
}
Run Code Online (Sandbox Code Playgroud)

背景.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");
  }
});
Run Code Online (Sandbox Code Playgroud)

wOx*_*xOm 7

ManifestV3 中的后台脚本是service worker现在的,因此它无法访问仅在windowHTML5 localStorage 或 DOM 等上公开的内容。顺便说一句,服务工作者没有window,他们的全局上下文是selfglobalThis

解决方案是切换到chrome.storage.local。这是一个完全不同的存储,可在所有扩展上下文中使用,包括内容脚本。请注意,a)它是异步的,因此用法不同;b)由于Chrome 中的错误,它当前不会返回 Promise ,所以你不能await这样做。在修复之前,请使用文档中显示的回调版本。

储存:

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

在弹出窗口中阅读:

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