javascript - Using Google Chrome extensions to import/export JSON files? -


i'm creating google chrome extension @ moment , wondering if it's possible both create json files download (export) , create button users can make extension open , parse json files have saved in local file system or on usb stick (import)?

the parsing of each json local file system involve reading off each key-value pair , doing data. have deal strings, nothing complicated.

**edit: **my question not duplicate of this one because i'm not interested in changing user's download path. want enable them to, consent, download file normal download directory (which filesaver.js can do). plus, post says nothing importing.

you can fake link "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 export/download array json file named vname variable.


if wish import/read file:
create input element (type=file) , make invisible (here i'm having html element , 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 element), can style wish , used trigger 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 imported data, , here should know (save storage, etc.)    ......   importorig.value = ''; //make sure clear input value after every import } 

Comments