简体   繁体   中英

How to save data with pwa

I am working on my own project where I want to create an application, which runs on android and iOS. I decide using HTML, CSS and JavaScript for creating a PWA. The app should enable the user to manage recips for tart incl. Cost calculation. My problem is, that I want to save the recips/ingredients in form of a table. The data should be stored permanently locally on the device. With the method "localstorage" the data are only saved temporarily. I don't want to host a webserver/database. The data should not be lost when the user delete the local cache of the browser. Is it possible to store general data with java script, for example in a text file, outside of the browser's cache?

In your case indexedDB would be my go to solution. It can be deleted by a user as all data stored in the browser. Browser can't store data in text files (at least as per October 2021)

It is possible. but it's not straightforward it must be done manually by the user. You can generate your DB as a downloadable file -eg. .txt or .csv - and provide the download link for the user or just auto-download it. here's an example.

function download(filename, text) {
  var element = document.createElement('a');
  element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
  element.setAttribute('download', filename);

  element.style.display = 'none';
  document.body.appendChild(element);

  element.click();

  document.body.removeChild(element);
}

// Start file download.
document.getElementById("dwn-btn").addEventListener("click", function(){
// Start the download of yournewfile.txt file with the content from the text area
    var text = document.getElementById("text-val").value;
    var filename = "yournewfile.txt";
    
    download(filename, text);
}, false);

to load the data you can create an import button that receives the data and populates the table. here's how you can read file data

function readImage(file) {
  // Check if the file is text.
  if (file.type && !file.type.startsWith('text/')) {
    console.log('File is not an textfile.', file.type, file);
    return;
  }

  const reader = new FileReader();
  reader.addEventListener('load', (event) => {
    img.src = event.target.result;
  });
  reader.readAsDataURL(file);
}

I recommend using this approach with indexedDb or local storage.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM