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
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
after wrapping it in a view.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:
Here's an example of the implementation:
// Reference to the form:
var form = document.forms["uploadForm"];
form.addEventListener('submit', function(ev) {
ev.preventDefault(); // Cancel submission
var fileInput = form.querySelector('input[type="file"]');
var file = fileInput.files[0];
if (!file) return; // No file selected
var fileReader = new FileReader();
fileReader.onload = function() {
var arraybuffer = fileReader.result;
// To manipulate an arraybuffer, wrap it in a view:
var view = new Uint8Array(arraybuffer);
view[0] = 0; // For example, change the first byte to a NULL-byte
// Create an object which is suitable for use with FormData
var blob = new Blob([view], {type: file.type});
// Now, the form reconstruction + upload part:
var formData = new FormData();
formData.append(fileInput.name, blob, file.name);
// ... handle remainder of the form ...
// Now, submit the form
var xhr = new XMLHttpRequest();
xhr.open('POST', form.action);
xhr.onload = function() {
// Do something. For example:
alert(xhr.responseText);
};
xhr.onerror = function() {
console.log(xhr); // Aw. Error. Log xhr object for debugging
}
xhr.send(formData);
};
fileReader.readAsArrayBuffer(file);
});