Skip to content

Instantly share code, notes, and snippets.

@panzi
Created March 6, 2024 18:51
Show Gist options
  • Select an option

  • Save panzi/9be026f8ee5a727b633bfcf056b565ec to your computer and use it in GitHub Desktop.

Select an option

Save panzi/9be026f8ee5a727b633bfcf056b565ec to your computer and use it in GitHub Desktop.

Revisions

  1. panzi created this gist Mar 6, 2024.
    45 changes: 45 additions & 0 deletions export_local_storage.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,45 @@
    // bookmarklet:
    // javascript:(function()%7Bconst%20blob%3Dnew%20Blob(%5BJSON.stringify(localStorage)%5D%2C%7Btype%3A'application%2Fjson'%7D)%3Bconst%20link%3Ddocument.createElement('a')%3Bconst%20url%3DURL.createObjectURL(blob)%3Blink.href%3Durl%3Blink.download%3D'local_storage.json'%3Blink.style.display%3D'none'%3Bdocument.body.appendChild(link)%3Blink.click()%3BsetTimeout(()%3D%3E%7BURL.revokeObjectURL(url)%3Bdocument.body.removeChild(link)%3B%7D%2C250)%3B%7D)()%3B
    function exportLocalStorage(){
    const blob = new Blob([JSON.stringify(localStorage)],{type:'application/json'});
    const link = document.createElement('a');
    const url = URL.createObjectURL(blob);
    link.href = url;
    link.download = 'local_storage.json';
    link.style.display='none';
    document.body.appendChild(link);
    link.click();
    setTimeout(() => {
    URL.revokeObjectURL(url);
    document.body.removeChild(link);
    }, 250);
    }

    // bookmarklet:
    // javascript:(function()%7Bconst%20input%3Ddocument.createElement('input')%3Binput.type%3D'file'%3Binput.onchange%3Dasync()%3D%3E%7Btry%7Bif(input.files.length%3E0)%7Bconst%20text%3Dawait%20input.files%5B0%5D.text()%3Bconst%20data%3DJSON.parse(text)%3Bif(!data%7C%7Ctypeof%20data!%3D%3D'object')%7Bthrow%20new%20TypeError('Not%20a%20valid%20local%20storage%20file!')%3B%7Dfor(const%20key%20in%20data)%7BlocalStorage.setItem(key%2Cdata%5Bkey%5D)%3B%7Dalert('Imported%20Local%20Storage!')%3B%7D%7Dcatch(error)%7Balert(error.message)%3Bconsole.error(error)%3B%7Ddocument.body.removeChild(input)%3B%7D%3Binput.style.display%3D'none'%3Bdocument.body.appendChild(input)%3Binput.click()%3B%7D)()%3B
    function importLocalStorage(){
    const input = document.createElement('input');
    input.type = 'file';
    input.onchange = async () => {
    try {
    if (input.files.length > 0) {
    const text = await input.files[0].text();
    const data = JSON.parse(text);
    if (!data || typeof data !== 'object') {
    throw new TypeError('Not a valid local storage file!');
    }
    for (const key in data) {
    localStorage.setItem(key, data[key]);
    }
    alert('Imported Local Storage!');
    }
    } catch (error) {
    alert(error.message);
    console.error(error);
    }
    document.body.removeChild(input);
    };
    input.style.display='none';
    document.body.appendChild(input);
    input.click();
    }