Reputation: 1138
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
Reputation: 73686
In Chrome/chromium, chrome.storage
, just like extension messaging, supports only JSON-compatible types:
BigInt
true
and false
null
but not undefined
Symbol
{}
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.
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
})
Storing:
chrome.storage.local.set({foo: [...map]})
Reading:
chrome.storage.local.get('foo', data => {
const map = new Map(data.foo);
// use it here
})
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