title: JS - open PDF in new Tab via XHR - with filename and auth header
body: <p>Thank you for reading!</p>
  
  <p>I want to open a PDF from a REST backend that gets loaded via XHR in a new tab with specified filename and Authorization header.</p>
  
  <p>So far I managed to download it with this (incl. auth headers and filename):</p>
  
  <pre><code>// saves XHR stream as file with configurable filename
  downloadXHRFile:function(endpoint,data,method,filename,errorcallback,mimetype){
  
     bsLoadingOverlayService.start();
  
     var def = $q.defer();
  
     var token = localStorageService.get('token');
     var xhr = new XMLHttpRequest();
  
     xhr.open(method, CONFIG.URL+endpoint, true);
     xhr.setRequestHeader('Authorization', 'Bearer '+token);
     xhr.setRequestHeader('Content-Type', 'application/json');
  
     xhr.responseType = 'arraybuffer';
  
     xhr.onload = function(e) {
        if (this.status == 200) {
           var blob=new Blob([this.response], {type:mimetype});
           var link=document.createElement('a');
           link.href=window.URL.createObjectURL(blob);
           link.download=filename;
           link.click();
           bsLoadingOverlayService.stop();
        }else{
           bsLoadingOverlayService.stop();
           errorcallback(xhr.statusText);
        }
        def.resolve();
     };
     xhr.send(
        JSON.stringify(data)
     );
  
     return def;
  },
  </code></pre>
  
  <p>Further I managed to open it in a new tab with the following code (incl. auth headers).
  Unfortunately the URL (and by that the filename) looks like this:</p>
  
  <p>blob:<a href="http://localhost:3000/0857f080-d152-48c6-b5fb-6e56292db651" rel="nofollow noreferrer">http://localhost:3000/0857f080-d152-48c6-b5fb-6e56292db651</a></p>
  
  <p>Probably it can be solved somehow like above but I cant find the solution.
  Does someone have a clever idea how I could set the filename in the new Tab?</p>
  
  <pre><code>// opens XHR filestream in tab
  openXHRFile: function(endpoint,filename,errorcallback){
  
     var token = localStorageService.get('token');
     var our_url = CONFIG.URL+endpoint;
  
     var win = window.open('_blank');
  
     downloadFile(our_url, function(blob) {
        var url = URL.createObjectURL(blob);
        win.location = url;
     });
  
     function downloadFile(url, success) {
        var xhr = new XMLHttpRequest();
        xhr.open('GET', url, true);
  
        xhr.setRequestHeader("Authorization", 'Bearer '+token);
        // xhr.setRequestHeader('Content-Type', 'application/json');
  
        xhr.responseType = "blob";
        xhr.onreadystatechange = function() {
           if (xhr.readyState == 4) {
              if (success) success(xhr.response);
           }else{
  
           }
        };
        xhr.send(null);
     }
  },
  </code></pre>