DEV Community

loading...

Namespacing Chrome Storage for page dependant settings for your Chrome Extension

datsgabs profile image Gabriel Lazcano ・2 min read

Link to original article with code snippets (recommended): https://gabriellazcano.com/blog/namespacing-chrome-storage-for-page-dependant-settings-in-your-chrome-extension/

As far as I know chrome.storage saves it’s keys globally, so it’s not like localstorage on normal pages that gets only works in the current page. For that purpose I had to figure out a way of achieving this. So I decided using namespaces using template literals. This is a really made up process so there might be inaccuracies, feel free to let me know :)

Creating the extension

Creating the extension from scratch is pretty straightforward, we just have to add a manifest.json file.

We have to create a popup.html file and just use it as if it was a normal HTML. We can import scripts add stylsheets, etc.

In the popup.js file is where we are going to have the logic for namespacing chrome.storage keys.

Firstly, I have to point out that chrome.storage is an async api therefore we will have to use async/await on our main function.

Then we going to use the tab API, that we enabled before in the manifest, to get the URL of the current page and we wait for the Promise to resolve. Then we use the storage api and use a template literal to get the settings only from the current URL. As we have no real way of getting the key from the results, we just resolve the first element in the Object.values() that returns an array of all the keys in the results which in this case is the settings object we want. Then we substitute the default settings object with the one we got from storage. To conclude, it works.

To set up a new element we have to set the addEventListener inside the async function as we’ll need the URL for setting up the namespace.

Wrap up

I hope you will find this blog post useful and keep it handy for a quick reference. This solution is a little clumsy but I didn’t find any better way and wanted to share it with you. Feel free to send me a DM or to mention me on Twitter if you’ve got any suggestion or fix.

You can look at the whole code in this repository

Discussion (0)

Forem Open with the Forem app