Jongwoo Lee
Jongwoo Lee

Reputation: 1138

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?

Upvotes: 5

Views: 1596

Answers (1)

woxxom
woxxom

Reputation: 73686

JSON types

In Chrome/chromium, chrome.storage, just like extension messaging, 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, function, Set, Map, RegExp, Date, and so on.
These will be stored as {}.

It doesn't support toJSON() customization methods, so if you want to use those you'll have to store JSON.stringify(obj) and call JSON.parse(str) when reading.

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)

Upvotes: 11

Related Questions