0

If I run window.open(..) is it possible to get response code of this new window request?

I wan't to download file from separate service in separate window, but the service can response with 200, 404 and 409. I need to properly handle this response code in main window.

Also if there is any cross browser solution?

Oleh Kurpiak
  • 1,066
  • 10
  • 23

1 Answers1

1

Short answer, no. Response codes are not included in the window object.

The only JavaScript solution to your problem using window.open would be if your service returns a copy of status codes in the document body. You could then parse that with (ES6):

const foo = window.open('http://stackoverflow.com');

foo.addEventListener('load', () => {
     console.log(foo.document.body.innerHTML);
     // or
     console.log(foo.document.body.innerText);
});

One big caveat is both pages need to be hosted on the same domain or you'll run into some cross-origin issues. I'm guessing this won't work for you.

An alternative solution would be creating a blob with XMLHttpRequest, saving the file to temporary storage, and then navigating the user there to download it. You would do that as follows (adapted from this SO answer) (ES6):

const xhr = new XMLHttpRequest();
xhr.responseType = 'blob';
xhr.addEventListener('load', () => {
    if (xhr.status === 200) {
         window.location = window.URL.createObjectURL(xhr.response);
    } else {
         // error handling
    }
});

xhr.send(postData);

This assumes you have a file that isn't normally read by the browser, if you need to download something like an image or video, use the download attribute as seen in the related linked answer. Also, depending on what browsers you want to support, you may need a polyfill for this solution. See CanIUse. Also note that this option also loads files into memory, so be wary of large files.

Finally, the most obvious and simple solution was the one @charlietfl mentioned in the comments, and that's handling this server-side. Depending on what language you're using, this is fairly easy.

Sheng Slogar
  • 1,162
  • 7
  • 15