b0nfire
b0nfire

Reputation: 33

Storing a HTML OBJECT Array inside Chrome Storage for a Chrome Extension

BACKGROUND:

I'm writing a chrome extension that when you access a certain page it finds all the table rows and then stores them and when you go back it shows you all the new values that have been added.

I want to store an array in storage so that when the user comes back to the page I can access it. Mainly to compare results each time to see if anything has changed.

Example.

myArray = [HTML OBJECT, HTML OBJECT, HTML OBJECT];  

on.window.unload {
    Chrome.storage.set(STORE MY ARRAY)
}

on.windows.onload {
    chrome.storage.get(MY STORED ARRAY AND SET TO OLD_myArray[])
}

function compareArrays() {
    TO DO STUFF WITH MY myArray[] and OLD_myArray[]
        e.g. comparing values to see if anything has changed.
}

I've tried local Storage but realised that It doesn't store arrays, So moved to Chrome storage.

I would like help getting myArray to store itself on unload and then set itself to OLD_myArray onload, So I can compare the values for the differences. Thanks.

Upvotes: 1

Views: 1378

Answers (1)

IronFlare
IronFlare

Reputation: 2322

In order to use chrome.storage, you need to use one of two methods:

  • chrome.storage.sync, which syncs saved data to any browser the user logs into.
  • chrome.storage.local, which only saves data to the current machine.

As the official documentation discusses, chrome.storage is implemented with callbacks, not with a return value from the get or set call itself.

// Save the current myArray value.
chrome.storage.local.set({'storedArray': myArray}, function() {
    console.log(`storedArray now contains ${myArray}.`);
});

// Retrieve the the stored value, defaulting to an empty array.
chrome.storage.local.get({'storedArray': []}, function(data) {
    console.log(`storedArray's value is ${data.storedArray}.`);
});

As an aside, it may not be a great idea to attach storage functions to an unload event, as the browsing context could terminate before the operation is complete. A browser crash, for instance, wouldn't call the window.unload event (this is only one of a number of situations which would interfere with your handler).

Upvotes: 2

Related Questions