【问题标题】:Setting local storage in a Chrome extension在 Chrome 扩展程序中设置本地存储
【发布时间】:2014-06-02 09:58:07
【问题描述】:

我正在使用以下代码在 Chrome 扩展程序中设置本地存储。

localStorage.setItem('userkey','123');

/* I've also tried this:
chrome.storage.sync.set({'userkey': 123}, function() {
          // Notify that we saved.
          message('Settings saved');
        });
*/

manifest.json:

{
  "manifest_version": 2,

  "name": "Shopaholic",
  "description": "All the latest sale items from your favourite clothes shops right on your home screen",
  "version": "1.0",

  "chrome_url_overrides": {
    "newtab": "index.html"
  },

"content_scripts": [
    {
      "matches": ["*://*/index.html"],
      "css": ["css/style.css"],
      "js": ["js/jquery.min.js"]

    }
  ],

 "options_page": "options.html",

"permissions": [
          "storage"
        ]
}

但是,我收到了这个错误:

未捕获的安全错误:无法读取“localStorage”属性 来自“窗口”:文档是沙盒的,缺少 “允许同源”标志。

如果我使用上面注释掉的代码,我会得到:

未捕获的类型错误:无法读取未定义的属性“同步”

我哪里出错了?

【问题讨论】:

  • 您是否使用 HTML 文档覆盖 newtab,然后将内容脚本注入该 HTML 文档?为什么不像往常一样直接在 HTML 标记中包含内容脚本文件?您能否更具体地说明您与 localStorage 交互的位置/上下文?
  • 从我的 manifest.json 中可以看出,我正在用一个名为 index.html 的文件覆盖新标签页。我正在尝试使用 localStorage 作为登录脚本的一部分来存储可以检查以查看用户是否已登录的用户密钥。

标签: javascript google-chrome google-chrome-extension local-storage


【解决方案1】:

阅读这个 - https://en.wikipedia.org/wiki/Same_origin_policy

基本上,它是一个 Web 应用程序安全模型概念。

因此,为避免这种情况,您需要在 google chrome 上禁用同源策略

因此,如果在桌面上,请使用此命令从命令行打开 chrome

chrome.exe --disable-web-security

然后运行你的脚本,它不应该给出这个错误!

【讨论】:

  • 谢谢,有没有办法在manifest.json 权限中解决这个问题?否则,扩展程序的每个用户都必须在命令行中禁用相同的源策略。
  • 你可以将这个添加到清单中 -- "permissions": [ "yourdomain.com", "storage" ]
  • 我的域名是什么?我试过 index.html 但它没有改变任何东西。
  • 如果你在本地托管它,那么 "localhost"
  • 添加类似 "permissions": ["localhost"]
猜你喜欢
  • 2011-07-16
  • 1970-01-01
  • 2012-12-06
  • 1970-01-01
  • 1970-01-01
  • 2011-01-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多