Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to fix TypeError: browser.storage is undefined in chrome/firefox web extension?

Note - this question is based off of this question (although it's not necessary to read the previous question): How to set value of textarea in different HTML file?

I have the following code, which is supposed to add a value into the local storage of firefox/chrome and then change the extension's UI (the code will differ slightly based upon which browser is being used, as of now, the code is for a extension in firefox):

function createSummaryBox(summary) {
    console.log("Setting textarea content to: " + summary);
    const currentSummary = {
        currentSummary: summary
    }
    browser.storage.local.set(currentSummary);
    window.location.href = '../summary_page/summary_page.html';
}

However, I get the following error whenever this function is called:

ReferenceError: browser.storage is not defined

How can I fix this error? I read through the MDN documentation on this method, so I'm not sure what I'm missing.

like image 270
Roymunson Avatar asked Apr 09 '18 23:04

Roymunson


People also ask

How to get undefined key in chrome storage?

chrome.storage.local.get('myKey', function(data) {console.log(JSON.stringify(data))}) and in that case ‘undefined’ is returned too. slosd

How to get undefined key from JSON string in chrome?

chrome.storage.local.get('myKey', function(data) {console.log(JSON.stringify(data))}) and in that case ‘undefined’ is returned too.

What happens to my data when Chrome is offline?

When Chrome is offline, Chrome stores the data locally. The next time the browser is online, Chrome syncs the data. Even if a user disables syncing, storage.sync will still work. In this case, it will behave identically to storage.local.

What is the chrome storage API?

Use the chrome.storage API to store, retrieve, and track changes to user data. This API has been optimized to meet the specific storage needs of extensions. It provides the same storage capabilities as the localStorage API with the following key differences:


1 Answers

as comments suggest, you need to declare permission.
In manifest.json add:

"permissions": [
    "storage"
],

or add it to any existing permissions:

"permissions": [
  "activeTab",
  "storage"
],

Mozilla doc page
Chrome doc page

Storage API can be used in content scripts.
Don't get confused, it's not an issue here, as it is in another Question linked in comments as possible duplicate, which it's not.

like image 54
papo Avatar answered Sep 20 '22 10:09

papo