GPT по быстрому накидал функций:
Сохранить:
javascript
function saveLocalStorageToFile() {
// Get all keys from local storage
const keys = Object.keys(localStorage);
// Create an object to store key-value pairs
const data = {};
// Loop through each key and add its value to the object
keys.forEach(key => {
data[key] = localStorage.getItem(key);
});
// Convert the object to JSON string
const jsonString = JSON.stringify(data);
// Create a new blob with the JSON string as its content
const blob = new Blob([jsonString], {type: 'application/json'});
// Create a link element to download the file
const url = URL.createObjectURL(blob);
const link = document.createElement('a');
link.href = url;
link.download = 'local-storage.json';
// Click the link to start the download
document.body.appendChild(link);
link.click();
// Clean up by removing the link and revoking the URL object
document.body.removeChild(link);
URL.revokeObjectURL(url);
}
// Call the function to save local storage to a file
saveLocalStorageToFile();
Загрузить
function loadLocalStorageFromFile(file) {
// Create a new FileReader object
const reader = new FileReader();
// Set a callback function for when the file is loaded
reader.onload = () => {
try {
// Parse the JSON string into an object
const data = JSON.parse(reader.result);
// Loop through each key-value pair and add it to local storage
Object.keys(data).forEach(key => {
localStorage.setItem(key, data[key]);
});
// Display a success message
console.log('Local storage has been updated.');
} catch (error) {
console.error(error);
}
};
// Read the file as text
reader.readAsText(file);
}
// Usage example: Load a file when the user selects it using an input element
const inputElement = document.createElement('input');
inputElement.type = 'file';
inputElement.addEventListener('change', event => {
const file = event.target.files[0];
loadLocalStorageFromFile(file);
});
document.body.appendChild(inputElement);
Надо будет в модуль завернуть ...