user817507
user817507

Reputation:

How to write localStorage data to a text file in Chrome

I want to write a localStorage item to a text file and want to invoke user to store the file in a specified location. Please help me with extending the code

  var data = JSON.parse(localStorage.getItem(pid));   
  var Text2Write = "";
  for(var pr in ele)
  {
     var dat = pr + ":" + ele[pr] + "\n";
     Text2Write += dat;
  }
  // Here I want to store this Text2Write to text file and ask user to save where he wants.  

Please help me extending this code.

Upvotes: 8

Views: 19114

Answers (5)

Maria Campbell
Maria Campbell

Reputation: 417

I also had wanted to save my local storage text to a file for download and the code works on desktop for Safari, Chrome and Firefox on Mac. However, I think it is impossible in iOS to save the Blob() anywhere with Chrome or Firefox. It does work, interestingly enough in Safari. For example, I can save the text file to my Wunderlist app. Here is the link my repo on Github: The Cat Whisperer on Github gh-pages

Here is the JavaScript code:

const fileDownloadButton = document.getElementById('save');
function localStorageToFile() {
    const csv = JSON.stringify(localStorage['autosave']);
    const csvAsBlob = new Blob([csv], {type: 'text/plain'});
    const fileNameToSaveAs = 'local-storage.txt';
    const downloadLink = document.getElementById('save');
    downloadLink.download = fileNameToSaveAs;
    if (window.URL !== null) {
        // Chrome allows the link to be clicked without actually adding it to the DOM
        downloadLink.href = window.URL.createObjectURL(csvAsBlob);
        downloadLink.target = `_blank`;
    } else {
        downloadLink.href = window.URL.createObjectURL(csvAsBlob);
        downloadLink.target = `_blank`;
        downloadLink.style.display = 'none';
        // add .download so works in Firefox desktop.
        document.body.appendChild(downloadLink.download);
    }
    downloadLink.click();
}
// file download button event listener
fileDownloadButton.addEventListener('click', localStorageToFile);      

Upvotes: 0

Michael Johansen
Michael Johansen

Reputation: 5116

Since the question is tagged with google-chrome-extension I want to provide a simpler solution for extension developers.

First, add "downloads" to permissions in manifest.json

"permissions": [
    "downloads"
]

Then use the downloads-API with the data:text/plain trick as provided by @emil-stenström.

var myString = localStorage.YOUR_VALUE;
chrome.downloads.download({
    url: "data:text/plain," + myString,
    filename: "data.txt",
    conflictAction: "uniquify", // or "overwrite" / "prompt"
    saveAs: false, // true gives save-as dialogue
}, function(downloadId) {
    console.log("Downloaded item with ID", downloadId);
});

To adapt for JSON, just prepare your object or array with JSON.stringify(localStorage.YOUR_DATA), then use data:text/json and change the file ending to .json

Upvotes: 2

Santiago Angel
Santiago Angel

Reputation: 1137

I found this console.save(data, [filename]) method you can add to the console that does the trick pretty easily. Note that when the file is downloaded it just goes directly into the default downloads folder. To add it simply run:

(function(console){

    console.save = function(data, filename){

        if(!data) {
            console.error('Console.save: No data')
            return;
        }

        if(!filename) filename = 'console.json'

        if(typeof data === "object"){
            data = JSON.stringify(data, undefined, 4)
        }

        var blob = new Blob([data], {type: 'text/json'}),
            e    = document.createEvent('MouseEvents'),
            a    = document.createElement('a')

        a.download = filename
        a.href = window.URL.createObjectURL(blob)
        a.dataset.downloadurl =  ['text/json', a.download, a.href].join(':')
        e.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null)
        a.dispatchEvent(e)
    }
})(console)

Then pass in the data and filename like so, console.save(data, [filename]) and the file will be created and downloaded.

Source:

https://plus.google.com/+AddyOsmani/posts/jBS8CiNTESM

http://bgrins.github.io/devtools-snippets/#console-save

Upvotes: 11

Emil Stenström
Emil Stenström

Reputation: 14126

If you don't want to use a server-side solution (does not have to be PHP of course), the easiest way is to use a data URI:

data:text/plain,Your text here

This will show the text file in the browser, and let the user save it where they want. I don't think it's possible to show a "Save as"-dialog for those kind of URI:s.

Note: this requires IE8 at least. But I'm guessing that's your requirement anyway, since you are using localStorage.

Upvotes: 4

Dion
Dion

Reputation: 3345

You have to write that content into a textfile which can be downloaded with PHP. With JavaScript this isn't possible I think. You could send an POST-request to a php file which can be downloaded as a text file.

Upvotes: -1

Related Questions