ZAR
ZAR

Reputation: 2736

Chrome Extension: Local Storage, how to export

I have a chrome extension that saves a bunch of data to chrome.storage.local. I'm trying to find easy ways to export this data and package it into a file. I'm not constrained on what type of file it is (JSON, CSV, whatever), I just need to be able to export the contents into a standalone (and send-able) file. The extension is only run locally and the user would have access to all local files.

Upvotes: 19

Views: 27341

Answers (4)

Vrushabh Ranpariya
Vrushabh Ranpariya

Reputation: 376

Export / Import Chrome LocalStorage

As per @RobW's Answer for export to a file, it worked, but no one posted anything to import it. so here is a simple function to import it:

var setObjectToLocalStorage = function(jsonData) {
    if (!(typeof jsonData === 'object' && !Array.isArray(jsonData) && jsonData !== null)) return false;
    for(var key in jsonData) {
        localStorage.setItem(key, jsonData[key]);
    }
}

// example
setObjectToLocalStorage({
  "theme": "dark",
  "settings": "{\"fontFamily\":[]}"
});

The exported file is in JSON so just use JSON content as a parameter in this function it will import those values the same as it is.
Note: If you don't find this information helpful, feel free to ignore it.

Upvotes: 0

njogued
njogued

Reputation: 9

You can create a blob, and simulate the download using an anchor tag.

chrome.storage.local.get(null, function(data) {
  var jsonData = JSON.stringify(data, null, 2);

  // Create a Blob containing the JSON data
  var blob = new Blob([jsonData], { type: 'application/json' });

  // Create a download link and trigger a click event to download the file
  var downloadLink = document.createElement('a');
  downloadLink.href = URL.createObjectURL(blob);
  downloadLink.download = 'extension_data.json';
  downloadLink.click();
});

Upvotes: 0

Rob W
Rob W

Reputation: 349222

First, you need to get all data.
Then serialize the result.
Finally, offer it as a download to the user.

chrome.storage.local.get(null, function(items) { // null implies all items
    // Convert object to a string.
    var result = JSON.stringify(items);

    // Save as file
    var url = 'data:application/json;base64,' + btoa(result);
    chrome.downloads.download({
        url: url,
        filename: 'filename_of_exported_file.json'
    });
});

To use the chrome.downloads.download method, you need to declare the "downloads" permission in addition to the storage permission in the manifest file.

Upvotes: 23

unit998x
unit998x

Reputation: 66

You should look here: https://groups.google.com/a/chromium.org/forum/#!topic/chromium-extensions/AzO_taH2b7U

It shows exporting chrome local storage to JSON.

Hope it helps

Upvotes: 0

Related Questions