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

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.

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
}

Related

Edit a file to be uploaded

I would like to be able to edit a file that has been selected for upload. I want to search and replace text in case absolute files should be made relative...
I notice in the File API I can do some of it, but I get a little stuck:
document.getElementById('exampleInputFile').onchange = function(event) {
var fileToLoad = event.target.files[0];
if (fileToLoad) {
var reader = new FileReader();
reader.onload = function(fileLoadedEvent) {
var textFromFileLoaded = fileLoadedEvent.target.result;
//Use logic to remove absolute files
//Upload S3
};
reader.readAsText(fileToLoad, 'UTF-8');
}
};
I am trying to figure out how now to convert that text to a proper File so that I can upload it to S3 using an existing api that expects something returned by: event.target.files[0] code above.
I do not want the server to handle any heavy lifting here if I can avoid it (files can easily be a few megabytes since they can be 3D models).
Assuming you know the url of the file when it lands in the S3 bucket, you can retrieve the file using a http.get, which will give you the contents of the (I assume plain text file). You can then parse that file and do whatever modification you need to do on the contents. If the file has changed, you can then write it back to the S3 bucket to replace the original file.
On AWS you can use Lambda to execute NodeJS code when an event is triggered (for example an upload to a specified bucket).

save a field value to a file on desktop

I am developing a custom application in "ServiceNow" which requires Javascript and HTML coding. So, I have a field say, "description" on my form. How may I save this field's value to a word document on the desktop?
While JavaScript cannot create a file for you to download by itself, ServiceNow does have a way for you to create one. Creating a Word document is impossible without the use of a MID server and some custom Java code, but if any file type will do you can create an Excel file using an export URL. To test this out, I made a UI Action in a developer instance running Helsinki on the Problem table. I made a list view that contains only the field that I wanted to save, and then used the following code in the UI action:
function startDownload() {
window.open("https://dev13274.service-now.com/problem_list.do?EXCEL&sysparm_query=sys_id%3D" +
g_form.getUniqueValue() + "&sysparm_first_row=1&sysparm_view=download");
}
When the UI action is used, it opens a new tab that will close almost immediately and prompt the user to save or open an Excel file that contains the contents of that single field.
If you want to know more about the different ways you can export data from ServiceNow, check their wiki-page on the subject.
You can use the HTML5 FileSystem API to achieve that
window.requestFileSystem(window.PERSISTENT, 1024*1024, function (fs) {
fs.root.getFile('file.txt', {create: true}, function(fileEntry) {
fileEntry.createWriter(function(fileWriter) {
var blob = new Blob([description.value], {type: 'text/plain'});
fileWriter.write(blob);
});
});
});
FYI, chrome supports webkitRequestFileSystem.
Alternatively, use a Blob and generate download link
var text = document.getElementById("description").value;
var blob = new Blob([text], {type:'text/plain'});
var fileName = "test.txt";
var downloadLink = document.createElement("a");
downloadLink.download = fileName;
downloadLink.href = window.webkitURL.createObjectURL(textFile);
downloadLink.click();
Javascript protects clients against malicious servers who would want to read files on their computer. For that reason, you cannot read or write a file to the client's computer with javascript UNLESS you use some kind of file upload control that implicitely asks for the user's permission.

Javascript & HTML File API- can a javascript object based on a file object still contain the file's location?

Say I have an array of user selected files.
In my application, each selected file corresponds to a person. Once the user selects the files, a table appears. In the left column is each file's name. In the right hand column, the user must fill in the name of the relevant person. Once all the names are filled in the user can upload the files. As there could be hundreds of names to fill in, I would like to be able to save the user's progress to localStorage periodically, in case the page refreshes.
I can pass each file object (var thisFile) to an uploading script and the browser will know where to locate the file.
However, I would like to be able to save the list of selected files in localStorage, and JSON.stringify will strip out a file object.
So say I first create a javascript object based on the file object (var file below).
If I then pass var file to the uploading script, will the browser still be able to locate the file, or would the full path to the file have been lost?
for (var i = 0; i < userSelectedFiles.length; i++) {
//File object (Stripped out by JSON.stringify).
var thisFile = userSelectedFiles[i];
//Create a javascript object based on the file object (Not stripped out by JSON.stringify).
var file: {
'lastModified': thisFile.lastModified,
'lastModifiedDate': thisFile.lastModifiedDate,
'name': thisFile.name,
'size': thisFile.size,
'type': thisFile.type
},
}
After more research, I have found that a file must be reselected after a browser refresh- the location of a file cannot be stored in localStorage.
You can save files to offline storage.
Read this article about offline storage offline_storage and quota-research
Read documentation LocalFileSystem
You can test offline storage here test page
How to use link
Here is the example for WebKit browsers (chrome and opera) of creating a file -> info.txt with your content, you need to ask a user of storage quota, in this example, is 10mb.
var maxSize = 1024 * 1024 * 10;
var onError = function() {};
var requestFs = window.requestFileSystem ||
window.webkitRequestFileSystem ||
window.mozRequestFileSystem ||
window.msRequestFileSystem || undefined;
var onRequest = function(grantedSize) {
requestFs(window.PERSISTENT, grantedSize, function(filesystem) {
filesystem.root.getFile("info.txt", {create: true}, function(DatFile) {
DatFile.createWriter(function(DatContent) {
var blob = /** your file or blob*/;
DatContent.write(blob);
});
});
}, onError)
};
navigator.webkitPersistentStorage.requestQuota(maxSize, onRequest, onError);

Web Development Displaying Local Files

Based on research, I've found tutorials, such as this one from Eric Bidelman, that go into FileReader usage. Instead of local files, these tutorials use files provided by the user. Modifying these examples to try and display local files were not successful.
After some research I've found that most browsers by default do not allow access to local files [1]. Some recommend using unsafe modes for testing, but that's not what I'm looking for as that would apply to only my testing [2].
Currently I allow the download of log files. My goal here with FileReader was to provide a way to view the files as well. Is there a way to achieve this? I'm coming up with blanks and have almost resigned to only allowing downloads instead of adding viewing. The following is example code of local file reading. This code fails since 'logpath' is not of type blob. I believe my question doesn't really require code, but I provided an example anyway.
HTML Code
<select name="loglist" id="loglist" onchange="run()" size="2">
<option>stack1.log</option>
<option>stack2.log</option>
</select>
Javascript
function run() {
var reader = new FileReader();
log = document.getElementById( "loglist" ).value;
var logdir = "/var/log/";
var logpath = logdir.concat(log);
reader.onload = function() {
logtext = reader.result;
alert(logtext);
}
reader.readAsText(logpath);
}
There is no way for JavaScript, embedded in a webpage, to access files on the user's local system other than through the File API when the user selects the file using a file input. It is not possible for the page to supply the file name to be opened.
var inp = document.querySelector("input");
inp.addEventListener("change", show);
function show(e) {
var f = this.files[0];
var r = new FileReader();
r.addEventListener("load", display);
r.readAsText(f);
function display(e) {
document.body.appendChild(
document.createTextNode(
e.target.result
)
);
}
}
<input type="file" id="input">

Parse a local file to an array using JavaScript

I am trying to read a local file and have each line as an index in an array using JavaScript. I have been searching for the past 20 minutes and either I'm stupid or there really isn't an answer that pertains to my problem (...but it's probably the former :P). I am really new to JavaScript so if you have an answer could you please comment the code just to I know what's going on?
Also, from the searching I've done on the internet some people said JavaScript can't read local file for security reasons so if that is correct is there another language I can use? I'm a bit familiar with PHP if that is an option, which I doubt it is.
EDIT
As per thg435's question, I'll explain what I am trying to accomplish.
My project is to analyze a BUNCH of water quality data that has been collected by the Ontario gov't (which I've done) and display it in some way. I have chosen to display it on a webpage using the Google Maps API. I currently have a file of chemicals that were found. Each line is a different chemical. I would like to read the file in an array then create an option menu displaying the chemicals in the array.
Also, the local file I would like to read will the be the same name and location all the time. I have seen people have boxes where the user clicks and chooses their file or to drag and drop but that's not what I'm looking for.
I don't think I explained this properly. I have a file in the same directory as my HTML and JavaScript files that contains words. Example:
Line 1: "Iron"
Line 2: "Aluminum"
Line 3: "Steel"
etc...
I would like to read the file and parse each line into a different index in an array. I don't want the user to be able to choose which file to read using the <input ... /> thing.
You're going to want to take a look at the FileReader API. This should allow you to read the text of a local file via readAsText(). This won't work in every browser but should work in all modern browser. You can see which browsers support it here.
Example:
<input id="file" type="file" />
var filesInput = document.getElementById("file");
filesInput.addEventListener("change", function (event) {
var files = event.target.files;
var file = files[0];
var reader = new FileReader();
reader.addEventListener("load", function (event) {
var textFile = event.target;
alert(textFile.result);
});
reader.readAsText(file);
});
It's not possible to invoke the FileReader API without user interaction. Consequently, your user would have to select whatever file to load in order for it to be read in pure JS. Since I'm assuming this will be up on a server, why not just put the list of chemicals also up on the server and GET the JSON encoded array of the results. Then you can decode them with Javascript.
You can access local files in 2 ways that I know of. The first way is making the user drag-and-drop the files onto the page, and using an <input type="file"> tag.
For the former, you would need to do the following:
addEventListener('dragover', function(e){e.preventDefault();});
addEventListener('drop', function(e) {
eventHandler.call(e.dataTransfer||e.clipboardData);
e.preventDefault();
});
For the latter, you'd need to add an event listener for the change event on the input:
document.getElementById('upload').addEventListener('change', eventHandler)
And for both, you'd need to have this as a basic callback function:
function eventHandler() {
var file = this.files[0]; //get the files
var reader = new FileReader(); //initiate reader
reader.onloadend = callbackFn; //set event handler
reader.readAsText(file); //initiate reading of files
if (this.id) { //only run if this is the input
var id = this.id;
this.outerHTML = this.outerHTML; //this resets the input
document.getElementById(id).addEventListener('change', eventHandler); //reattach event handler
}
function callbackFn(e) {
document.getElementById('output').value = e.target.result; //output it to a textarea
}
}
Here is a demo where the text contents (that what you see when opening it in notepad) of any file you drop in it, or any file you select from the input, is put in the textarea.
For more information, see https://developer.mozilla.org/en-US/docs/Using_files_from_web_applications.

Categories

Resources