'Can chrome.storage save "advanced" objects like Date or Map?

I made a chrome extension that manages internet history, browser cookies, etc. I'm trying to make a notification if you don't run it for a week, so I used chrome.storage to save the timestamp whenever you use the extension.


Here's my code:

<popup.js>

function clear()
{
chrome.browsingData.removeHistory({"since":0}, callback);
var now = new Date();
chrome.storage.local.set({key: now}, function() {
console.log('Value is set to ' + now)
}

(callback is an empty function)


<background.js>

chrome.storage.local.get(["key"], function(result) {
alert (result.key)
});

When I tested this, it gave me:

[object Object]

Why is this code giving me this, not the timestamp I saved?



Solution 1:[1]

JSON types

chrome.storage, just like extension messaging in Chrome, supports only JSON-compatible types:

  • numbers but not BigInt
  • strings
  • boolean true and false
  • null but not undefined
  • objects/arrays consisting of the above simple types
    • can be nested
    • can't have circular self-references
    • the keys must be strings not Symbol
    • the unsupported portion will be stripped so a complex type will produce {}

It doesn't support DOM elements, class instances, Set, Map, RegExp, Date, and so on.
These will be stored as {}.

To see what will be actually stored, run this in your code or in devtools console:

console.log(JSON.parse(JSON.stringify(obj)))

Solution for Date

Store Date.now() which is a number:

chrome.storage.local.set({foo: Date.now()})

To recreate a date:

chrome.storage.local.get('foo', data => {
   const date = new Date(data.foo);
   // use it here
})

Solution for Set/Map

Storing:

chrome.storage.local.set({foo: [...map]})

Reading:

chrome.storage.local.get('foo', data => {
   const map = new Map(data.foo);
   // use it here
})

Alternatives for media objects

  • Convert to a data URI string.
  • Convert to ArrayBuffer and store in IndexedDB.

P.S. Don't use + to concatenate strings and objects in console.log. Use , like this: console.log('Value is set to', now)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1