#JavaScript #Snippets July 07, 2023

JavaScript: Exporting and Importing localStorage Data

1. Press the F12 or Fn + F12 keys to open the Dev Tools or Console. 2. Navigate to the Console tab 3. Copy and Paste the code below. 4. Press Enter to execute the code

Exporting

// Create a new empty object to store the data
const data = {};

// Loop through the local storage and add each key-value pair to the data object
for (let i = 0; i < localStorage.length; i++) {
  const key = localStorage.key(i);
  const value = localStorage.getItem(key);
  data[key] = value;
}

// Convert the data object to a JSON string and encode it for use in a data URL
const dataStr = `data:text/json;charset=utf-8,${encodeURIComponent(JSON.stringify(data))}`;

// Create a new anchor element for the download link
const downloadAnchorNode = document.createElement('a');

// Set the href and download attributes of the anchor element
downloadAnchorNode.href = dataStr;
downloadAnchorNode.download = 'localstoragedata.json';
// Append the anchor element to the document body
document.body.appendChild(downloadAnchorNode);

// Programmatically click the anchor element to initiate the download
downloadAnchorNode.click();

// Remove the anchor element from the document
downloadAnchorNode.remove();

Importing

// Create an input element
const input = document.createElement('input');
input.type = 'file';

// Listen for the change event on the input element
input.addEventListener('change', () => {
  const file = input.files[0];

  // Read the contents of the file
  const reader = new FileReader();
  reader.onload = (e) => {
    const data = JSON.parse(e.target.result);

    // Loop through the data and set each key-value pair in the local storage
    for (const [key, value] of Object.entries(data)) {
      localStorage.setItem(key, value);
    }
  }
  reader.readAsText(file);
});

// Click the input element to prompt the user to upload the file
input.click();

SEARCH