Download Force to Google Chrome Extension

I am writing a Google Chrome extension that allows you to upload a backup file of your data. I want the user to be able to click the button and the "Save As" dialog box will open and they will be able to save the file on their computer. Nothing works and I did not find the answer on the Internet. I tried several approaches:

  • Usage document.execCommand('SaveAs', null, 'filename.json');This does not work because this command is only for IE and does not seem to be an alternative to Webkit
  • Using data URIs . This was the most promising and worked in Opera and Firefox, but the problem is that neither Chrome nor Safari seem to support Content-disposition = attachment; -header in the URI. This one should work. (Chrome doesn't even allow me a ctrl/cmd+spage from a data URI)
  • Use XMLHTTPRequest. I have not tried this, but there must be some way in which you could pass the request? Please note that I do not want to use an external server (in this case, I could just send a POST request and apply Content-disposition: -header)
  • Use the available Chrome extension API. But there seems to be nothing for this purpose.

The reason why I do not want to use any external server is that I do not want to pay for hosting, and the data sent can be sensitive to the user, and I do not want to violate anyone's privacy.

Has anyone got this to work?

+5
source share
1 answer

I did this as follows in the Appmator code on Github.

The basic approach is to create your Blob, but you want (Chrome / WebKit / Firefox has a responseBlob on XmlHttpRequest so you can use it), create an iframe (hidden, display: none), then set the src iframe to be Blob.

. , .

var savaeas = document.getElementById("saveas");
var bb = new (window.BlobBuilder || window.WebKitBlobBuilder)();

var output = Builder.output({"binary":true});
var ui8a = new Uint8Array(output.length);

for(var i = 0; i< output.length; i++) {
  ui8a[i] = output.charCodeAt(i);
}

bb.append(ui8a.buffer);

var blob = bb.getBlob("application/octet-stream");
var saveas = document.createElement("iframe");
saveas.style.display = "none";

if(!!window.createObjectURL == false) {
  saveas.src = window.webkitURL.createObjectURL(blob); 
}
else {
  saveas.src = window.createObjectURL(blob); 
}

document.body.appendChild(saveas);
+3

All Articles