I am setting some values at the option page. This is now working okay. But i am unable to access the data setted in the background.html or in the content script. I have read tha
Content scripts cannot directly read the localStorage values from the background page. If you wish to read localStorage key-value pairs, see this answer which provides an explanation plus code for achieving this: Accessing global object from content script in chrome extension
Although the previous method works, I recommend the chrome.storage API instead: This can be used by all extension pages. A huge difference between localStorage
and chrome.storage
is that chrome.storage
is an asynchronous API.
Here's an example to illustrate the dfferences:
// synchronous localStorage
localStorage.setItem('keyname', 'value');
alert(localStorage.getItem('keyname'));
// asynchronous chrome.storage
chrome.storage.local.set({keyname: 'value'}, function() {
chrome.storage.local.get('keyname', function(items) {
alert(items.keyname);
});
});
On the first sight, the chrome.storage
API looks more convoluted. However, if you want to save data within an extension, it's the best way to do so. The localStorage
approach takes much more code (see the answer I linked on top of this answer) to achieve the same functionality. And, it's also asynchronous.