In this post, we're going to use chrome.storage
API to store, retrieve, and track changes to user data in the chrome extension.
If you are building your first chrome extension than you might stumble across a problem of storing user data specific to each site. Using chrome.storage
API is the easiest way to solve the problem and it can also help you to establish a indirect communication channel between the extensions and the content scripts.
So let's get started!
1. To use the storage API, declare the "storage" permission in the extension manifest. For example:
{
"name": "My extension",
...
"permissions": [
"storage"
],
...
}
2. Create a file storage.ts
which will act as a storage utility file to keep all the methods you need to work with chrome.storage
Api. For example:
The setter and getter will help you to store and retrieve user data from chrome extension local storage.
3. Now you can import localStorage
from storage.ts file in your extension or in your content script. For example
import { localStorage } from '../shared/storage';
// To get the data from local storage use follow
localStorage .get((userData) => {
// do something
})
// to save the data simply use
localStorage.set(userData);
Note Think of adding to storage as being like putting something in a pipe. The pipe may have material in it already, and it may even be filled. Always assume a delay between when you add to storage and when it is actually recorded
4. In your content script you can listen to the changes done to stored data by adding the following
localStorage.listen(updateDom);
The listen method will need a callback function which will be called every time any changes is done to stored user data. Hence it act as communication channel between content script and the extension. you can now easily update the dom
or trigger some content script work by updating the local storage in your extension.
You can find the complete code sample here
References
Top comments (0)