Jialiang Zhou
Jialiang Zhou

Reputation: 141

Not able to access storage in Content Scripts in Chrome Extension Manifest V3

I tried to access information stored in chrome.storage.session in my content script, but the browser keeps informing me that "Access to storage is not allowed from this context" even though I enabled "storage" in manifest.json

After fetching some data in my background script, I store the received

chrome.storage.session.set({"data": data});

However, when I try to access it in my content script by running the following line:

chrome.storage.session.get(["data"],function(data){console.log(data)})

I got the following error:

Uncaught TypeError: Cannot read properties of undefined (reading 'session')

However, when I run the exact same command in my background script, I was able to retrieve the data.

I also made sure I enabled "storage" permission in my manifest.json. Why is this happening?

Thanks so much in advance!

Upvotes: 14

Views: 27854

Answers (1)

woxxom
woxxom

Reputation: 73806

Access to storage is not allowed from this context

As the documentation says session is only for trusted contexts by default.

To enable it in the content scripts call setAccessLevel from such a trusted context i.e. in the background script or in an extension page like the action popup or options.

chrome.storage.session.setAccessLevel({ accessLevel: 'TRUSTED_AND_UNTRUSTED_CONTEXTS' });

Cannot read properties of undefined (reading 'session')

This error says that the parent of session is undefined i.e. chrome.storage is undefined, which can only happen in these cases:

  • you didn't reload the extension after editing manifest.json
  • an orphaned content script tried to access storage after you reloaded or updated the extension
  • your code is not a content script, but just a page script e.g. you ran it in a script element or injected with world: 'MAIN'.

Upvotes: 14

Related Questions