using my chrome extension i would like to grab a file(and maybe change it) before it gets uploaded to a website. Particularly from file-inputs. Put another way if i select a file with an input[type=file] i want my chrome extension to interrupt any submit and take the file. Then my extension applies its magic to the file and after that the file may be submitted/uploaded. How can i approach this?
On problem occurs with the file path. If i grab the vaule of a file-input it always changes the actual path to " C:\fakepath\" due to HTML5 standard and compatibility issues. How can i access the file then? Maybe it is saved temporarily in some chrome storage?
EDIT: Well, i managed to read the file selected in the file input like this:
var file;
$('input[type=file]').change(function(e){
file = e.target.files[0];
var reader = new FileReader();
reader.onload = function (event) {
console.log(event.target.result); //contains the file data
//maybe change data and use filewriter
};
reader.readAsDataURL(file);
};
Now i would like to use a FileWriter to write to e.target.files[0]
I followed this tutorial: http://www.html5rocks.com/en/tutorials/file/filesystem/ but i am not able to create a proper FileWriter.
It is not necessary to write to the original file on the disk - might not even possible - but i need to change the data that is used to upload in the corresponding file-input form field.
There's no defined API for a Chrome extension to intercept the payload of a request (work in progress).
That being said, you can use a Content script to add an event listener which:
ArrayBuffer
using theFileReader
API.ArrayBuffer
after wrapping it in a view.Blob
from the modified data.Reconstruct the form by creating a
FormData
instance, then use the.append(name, value[, filename])
method.Note: In the example below, I did not include the form reconstruction method. I only included the file upload part. There are two approaches to reconstruct the form:
XMLHttpRequest
. Note: If you're running this code in the context of your Chrome extension, don't forget to explicitly whitelist the URL at thepermissions
section in the manifest file.Here's an example of the implementation: