0

Stemming from a lack of finding a download manager I like on Ubuntu, I was wondering if it's possible to create one using HTML5 and JavaScript with the new File API available in Chrome. At the moment I'm working on a proof of concept which will just download a small file (Google's logo) from a remote URL into the sandbox file system. Code below:

window.requestFileSystem  = window.requestFileSystem || window.webkitRequestFileSystem;

function onError(e) {
    console.log('Error:', e)
}

var xhr = new XMLHttpRequest();
xhr.open('GET', 'https://www.google.co.uk/images/srpr/logo11w.png', true);
xhr.responseType = 'blob';

xhr.onload = function(e) {

    window.requestFileSystem(TEMPORARY, 1024*1024, function(fs) {

        fs.root.getFile('google.png', {create: true}, function(fileEntry) {

            fileEntry.createWriter(function(writer) {

                var blob = new Blob([xhr.response], {type: 'image/png'});

                writer.write(blob);

            }, onError);

        }, onError);

    }, onError);

}

xhr.send();

This seems like it'd work to me, however when running it won't allow me to download Google's logo due to Access-Control-Allow-Origin.

Due to this being relatively new I haven't been able to find the best way to achieve what I want using the new file API functions, so I'm not even sure if using a AJAX request is the best way to do it. If not, I'm open to suggestions. Otherwise, is there a way to get around the Access-Control-Allow-Origin problem?

I need to keep this 100% client side also, I can't use something like PHP to stream the file to the client or anything.

John Dorean
  • 3,744
  • 9
  • 51
  • 82

1 Answers1

1

XMLHttpRequest only works in current domain, unless you use CORS.

Since you have no control over Google's server, you can't use it, so yo can't access Google's files from your domain.

Of course, you could always use XMLHttpRequest to get a file from your server, which connects to Google and outputs the desired file.

Oriol
  • 274,082
  • 63
  • 437
  • 513
  • Also see [Ways to circumvent the same-origin policy](http://stackoverflow.com/questions/3076414/ways-to-circumvent-the-same-origin-policy) – Oriol Apr 12 '14 at 01:06
  • Okay, so using an AJAX request is out then, since I can't rely on the domain allowing me to use it and I can't have a server side solution either. Is there any other way I can download the file to Chrome's sandbox storage without using AJAX? – John Dorean Apr 12 '14 at 10:11
  • @ChrisWhite In order to save anything to Chrome's storage, you must have the data you want to save. And if that data comes from a file in a server, you must use AJAX to get it. – Oriol Apr 12 '14 at 16:55