chrome.storage.sync undefined?

2019-01-13 19:53发布

I'm trying to use chrome storage in an extension, via a content_script, but I keep failing on

Uncaught TypeError: Cannot read property 'sync' of undefined 

This is my code:

testChromeStorage();

function testChromeStorage() {  
    console.log("Saving");
    chrome.storage.sync.set({'value': theValue}, function() {
        message('Settings saved');
    });
    chrome.storage.sync.get("value", function (retVal) {
            console.log("Got it? " + retVal.value);
    });
}

4条回答
老娘就宠你
2楼-- · 2019-01-13 20:35

Reload the Extension

I had the "permissions" key added in my manifest file but still I struggled to get this fixed.

After adding the permission:-

"permissions": [
    "storage"
 ]

Goto your extension using: chrome://extensions/ & click the Reload button:-

enter image description here

查看更多
三岁会撩人
3楼-- · 2019-01-13 20:38

If someone was facing this issue on Firefox, please note, that it is not supported yet:

https://developer.mozilla.org/en-US/Add-ons/WebExtensions/API/storage#Chrome_incompatibilities

For my purposes it was sufficient to replace chrome.storage.sync by chrome.storage.local.

Regarding the Firefox implementation state it might be worth to look also here from time to time:

http://arewewebextensionsyet.com/#storage

查看更多
【Aperson】
4楼-- · 2019-01-13 20:40

You have to add the "storage" permission in your manifest.json file, i.e.:

...
  "permissions": [
    "storage"
  ],
...

For more information, see: https://developer.chrome.com/extensions/storage

查看更多
仙女界的扛把子
5楼-- · 2019-01-13 20:48

See https://developer.chrome.com/extensions/content_scripts.html:

However, content scripts have some limitations. They cannot:

Use chrome. APIs (except for parts of chrome.extension)*

(emphasis added)

查看更多
登录 后发表回答