0

I'm trying to open a PDF file in a new tab (or window depending on the browser config). Currently if I specify the href for a local file it works as expected, but I need to provide a link that dynamically generated by an API.

So basically: <a href="/assets/test.pdf" target="_blank">PDF</a>--> this works (opens the file in a new tab)

<a href="https://my-pdf-url" target="_blank">PDF</a>--> this opens a new window, closes it immediately and download the file.

I believe this is a security measure by the browser, but is there any way to get around this behavior and show it in a new tab?

lmalves
  • 137
  • 2
  • 11
  • The site you're loading the file from must be sending a `content-disposition: attachment` header, which forces the browser to download the file. – Richard Deeming Dec 10 '21 at 14:11
  • Possible solution https://stackoverflow.com/questions/43270793/angular-2-how-to-display-pdf-file – glx Dec 10 '21 at 14:12
  • @RichardDeeming it does not include that header but includes ```content-type: binary/octet-stream``` and I believe it should include ```application/pdf; charset=UTF-8```. Unfortunately I have no control over the API that returns the file or the link – lmalves Dec 10 '21 at 14:58
  • @glx My first attempt to fetch the file contents and convert it to Blob with the correct content-type gave me a CORS error on the API. – lmalves Dec 10 '21 at 15:00
  • 2
    That would do it - the browser doesn't understand what file type is being returned, so it offers to download the file for you. If you can't get the third-party to fix their API, and the CORS headers prevent you from loading the file in Javascript, I suspect you'll need some sort of proxy handler on your own server to retrieve the file and return it with the correct headers. – Richard Deeming Dec 10 '21 at 15:01

1 Answers1

0

You can use JS window.open to open the PDF in a new tab:

    <a onclick='window.open("https://the_URL_here.somewhere.some","_blank")'>Open PDF in a new tab</a>

Or call a function that runs the window.open command. Another way would be to generate the link and add it to a layer using getElementById() using the innerHTML property.

  • Thanks for the suggestion but it has the same result – lmalves Dec 10 '21 at 14:56
  • I see. The code works. However, you need to send a specific response header to make the browser behave like you want: Content-Disposition : inline However, if you can't, the solution linked in the comments might do it. – Enrique González Dec 10 '21 at 15:33