16

I have written a Chrome extension. I cannot use localStorage.setItem and localStorage.getItem for storing and retrieving because background and browser action runs in different environment [as seen here].

So I decided to use the Chrome storage API:

var storage = chrome.storage.local;
var myTestVar = 'somevar';
var obj = {};
obj[myTestVar] = $("#somevar").val();
storage.set(obj);

which produced the following error:

Uncaught TypeError: Cannot read property 'local' of undefined

What am I doing wrong?

Community
  • 1
  • 1
Milind Anantwar
  • 81,290
  • 25
  • 94
  • 125

2 Answers2

21

Make sure that all necessary permissions have been declared in the manifest file. "storage", in your case.

In general, the following steps should fix the problem of apparently undefined Chrome APIs:

  1. Read the documentation of the API you're using and get yourself familiar with the prerequisites, usually manifest permissions (e.g. chrome.storage#manifest).
  2. Check if your (user's) Chrome version supports the API, by looking at What's new.
  3. Check if the script is running in the right context. Most APIs are only available to the extension's process. (the chrome.storage API can also be used in content script though)
  4. Otherwise, resort to your usual debugging skills: Typos, variable shadowing, ...
Community
  • 1
  • 1
Rob W
  • 341,306
  • 83
  • 791
  • 678
  • Adding one more point, In case if you forget to reload, go to the extension settings and restore the specific extension you are working with after the change in manifest file. – Sandy B Oct 21 '22 at 08:48
1

You'll get this error if you try running your app as a simple HTML page opening the HTML file in Chrome.

Add the app in Chrome properly (as an Extension) then run it.

Vitalicus
  • 1,188
  • 13
  • 15