Search code examples
javascripthtmlgoogle-chromegoogle-chrome-extensionstorage

chrome.storage.sync returned as undefined


Hello,

I have been recently receiving an error that goes by Uncaught TypeError: Cannot read properties of undefined (reading 'sync') whilst coding my Chrome Extension. Though I have read and modified my document enough WHILST doing a deep dive to find the root of this problem, I am still running into a big error.

I am trying to use the storage to store a boolean that will determine if a button is shown or not.
Trying to find the source of the many errors I was getting, I found that chrome.storage.sync was the only one I couldn't fix myself.

Quick note: If you respond with plain Javascript, please tell me where to place it as that might be off too. I am executing this script from an HTML page and would not like it to be in a background script (if that is possible).

My code goes like so:
manifest.json

  "permissions": [
    "storage"
  ],
  "background": {
    "service_worker": "background.js"
  },
  "action": {
    "default_icon": "images/icon-48.png",
    "default_popup": "popup.html"
  },
  "content_scripts": [
    {
      "matches": ["###"],
      "js": ["inject.js"]
    }
  ],
  "sandbox": {
    "pages": ["popup.html"]
  }

popup.html: this is the page where I get an error

<body>
   <script>
        chrome.storage.sync.set({ "enabled": true }, function() {
            alert('set');
        });
   </script>
</body>

Error I am receiving: (if you need this)

Uncaught TypeError: Cannot read properties of undefined (reading 'local')
Context
popup.html
Stack Trace
popup.html:88 (anonymous function)

\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
chrome.storage.local.set({"enabled": true}, function() {     <<<<<------ line with error
            alert('set');
        });
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\

Solution

  • Please try this.

    manifest.json

    {
      "name": "hoge",
      "manifest_version": 3,
      "version": "1.0",
      "permissions": [
        "storage"
      ],
      "action": {
        "default_popup": "popup.html"
      }
    }
    

    popup.html

    <html>
    <body>
      <script src="popup.js"></script>
    </body>
    </html>
    

    popup.js

    chrome.storage.sync.set({ "enabled": true }, function() {
      alert('set');
    });