bagelboy bagelboy - 2 months ago 25
Javascript Question

HTML5 sessionStorage or chrome.storage for Chrome Extension?

I have a Chrome Extension that is only a content script. I want to persist some data that is calculated in the content script so I can easily access it while browsing without having to recalculate it on each page. I only need the data to be stored for the session.

I was looking at the chrome.storage API but it seems data will persist there past the session. I have previous experience using HTML5 sessionStorage, but I feel like I should be leveraging Google's API here.

Any input is appreciated, thanks!

Answer

Inside a content script, using sessionStorage will access and modify the sessionStorage of that site, not of your extension.

You must use chrome.storage.local if you want it to be available to content scripts on other sites and to avoid breaking the sites.

There is no automatic clearing of chrome.storage.local data, but you can create an event page that clears it on startup.

manifest.json:

"background": { "scripts": [ "background.js" ], "persistent": false }

background.js:

chrome.runtime.onStartup.addListener(function() {
 chrome.storage.local.clear()
})

chrome.storage.local.clear

chrome.runtime.onStartup

Event Pages