0

I am new to developing Chrome Extensions.

I am trying to get the values for one of the keys which is stored in my browser's localstorage (inspect -> Application -> Localstorage). What I want to do is in my Chrome Extension, when you click a button, I just need it to fetch the value from localstorage for the page which is open in my browser's current tab.

This is the JS function which I am using -

chrome.storage.local.get(['granted.selected'], function(result) {
            console.log('Value currently is ' + result.granted.selected);
         }); 

granted.selected - is the name of the key whose value I want to fetch.

When this executes, I get "Value currently is undefined" whereas I want it to fetch the values stored in the above key (granted.selected).

What do I need to add to have this fetch the value for that key from my current open tab's localstorage?

In short - Just want to access a webpage's localStorage from a Chrome extension.

Any help will be greatly appreciated. Thanks!!

wOxxOm
  • 43,497
  • 7
  • 75
  • 96

1 Answers1

0

chrome.storage.local is not localStorage, it's a completely different storage API.

localStorage is a DOM storage.
To access DOM of a web page you need a content script [1].
Here's an example of programmatic injection in the popup script or in the background script:

chrome.tabs.executeScript({
  code: 'localStorage["keyName"]'
}, ([result] = []) => {
  if (!chrome.runtime.lastError) {
    console.log(result);
    // use the result here inside the callback
  }
});

Notes:

  • You'll need permissions in manifest.json as explained in [1].
  • keyName is the name of the key as seen in devtools "Application" panel of the web page
  • each part of an extension has its own devtools console.
wOxxOm
  • 43,497
  • 7
  • 75
  • 96
  • Not necessarily you need a content script. he just needs to access the local storage which is a available in window object. Please learn here developer.mozilla.org/en-US/docs/Web/API/Window/localStorage – – Athish Murugan Apr 19 '20 at 12:59
  • A content script is necessary in this case. Extensions have multiple contexts and the question clearly states the OP wants to access localStorage of the web page which is only possible from a content script. – wOxxOm Apr 19 '20 at 13:20
  • Got it. Let me try out both the options and see if it works. Thanks for the help – Bhavik Thakkar Apr 27 '20 at 23:02