Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Chrome Extension: chrome.storage is undefined

I added the following code to my otherwise-working Google Chrome Extension…

var storage = chrome.storage ;
console.log("storage is " + storage) ;
var bookmarks = chrome.bookmarks ;
console.log("bookmarks is " + bookmarks) ;

Upon running, the console says

storage is undefined
bookmarks is [object Object] 

In other words, bookmarks works OK but storage is missing in action. My manifest has requested both…

{
   ...
   "permissions": [ "bookmarks", "tabs", "storage" ],
}

In case it matters, this extension is installed as an External Extension on Mac OS X. To make sure it was updated correctly, I copied the code above from the files installed into ~/Library/Application Support/Google/Chrome/Default/Extensions. And, of course, I've relaunched Chrome.

Why might chrome.storage be undefined?

like image 268
Jerry Krinock Avatar asked Feb 02 '13 01:02

Jerry Krinock


2 Answers

Edit: the answer below was written in 2013. Now in 2021, as Irfan wrote in comment:

chrome.storage is available from content script too. Your extension's content scripts can directly access user data without the need for a background page. https://developer.chrome.com/docs/extensions/reference/storage/

Original answer:

LocalStorage is only available in background pages and popup. If you need to acces to some data you will need to pass a message from your current page to a background page. Here is the code :

In your current page:

chrome.extension.sendMessage({action:"getstorage"}, function(response){
   console.log("storage is " + response.myVar);  
});

In the background page:

chrome.extension.onMessage.addListener(function(request, sender, sendResponse) {
  if (request.action == "focusWindow"){
    sendResponse({myVar: localStorage.myStorage});
  }
});

You can find more examples in the chrome documentation on Message Passing

like image 82
Paul Fournel Avatar answered Sep 28 '22 06:09

Paul Fournel


There is "Reload (Ctrl+R)" link inside extension on "Extensions" tab, clicking on it fixes the problem (I spent few hours). Nor disabling/enabling extension neither restarting Chrome browser will fix the problem. I hope it will save someone's time ;)

like image 39
Developer Avatar answered Sep 28 '22 07:09

Developer