Search code examples
javascriptjsongoogle-chromegoogle-chrome-extensiongoogle-chrome-app

Using Google Chrome extensions to import/export JSON files?


I'm creating a Google Chrome extension at the moment and I was wondering if it's possible for it to both create JSON files to download (export) and create a button where users can make the extension open and parse JSON files that they have saved in their local file system or on a USB stick (import)?

The parsing of each JSON from the local file system would simply involve reading off each key-value pair and doing something with the data. It would only have to deal with strings, so nothing complicated.

**EDIT: **My question is not a duplicate of this one because I'm not interested in changing the user's download path. All I want is to enable them to, with their consent, download a file to their normal download directory (which Filesaver.js can do). Plus, that post says nothing about importing.


Solution

  • You can fake link to "download" imaginary array MyData or whatever,:

    var MyArray = [elem1, elem2, ....];
    var _myArray = JSON.stringify(MyArray , null, 4); //indentation in json format, human readable
    
    var vLink = document.createElement('a'),
    vBlob = new Blob([_myArray], {type: "octet/stream"}),
    vName = 'watever_you_like_to_call_it.json',
    vUrl = window.URL.createObjectURL(vBlob);
    vLink.setAttribute('href', vUrl);
    vLink.setAttribute('download', vName );
    vLink.click();
    

    this will export/download your array into json file named as vName variable.


    If you wish to import/read file:
    create input element (type=file) and make it invisible (here I'm having html element and then adding js listener in script)

    <input type="file" id="importOrig" accept=".json" style="display:none"/>
    

    script

    importOrig.addEventListener("change", importFun, false);
    

    make button fakeImp (or any element), that you can style as you wish and that will be used as trigger for importing event

    fakeImp.onclick = function () {importOrig.click()}
    

    import function (from listener)

    function importFun(e) {
      var files = e.target.files, reader = new FileReader();
      reader.onload = _imp;
      reader.readAsText(files[0]);
    }
    
    function _imp() {
      var _myImportedData = JSON.parse(this.result);
      //here is your imported data, and from here you should know what to do with it (save it to some storage, etc.)
    
      ......
      importOrig.value = ''; //make sure to clear input value after every import
    }