Home > Web Front-end > JS Tutorial > How Can I Download Files in a New Tab or Window Using JavaScript/jQuery Without Replacing the Current Page?

How Can I Download Files in a New Tab or Window Using JavaScript/jQuery Without Replacing the Current Page?

Linda Hamilton
Release: 2024-12-15 21:44:11
Original
946 people have browsed it

How Can I Download Files in a New Tab or Window Using JavaScript/jQuery Without Replacing the Current Page?

Downloading Files Using JavaScript/jQuery Without Replacing Current Page

Problem:
How do you initiate a file download manually in a separate tab or window, while avoiding the default behavior of replacing the current page with the downloaded file using JavaScript/jQuery?

Solution:

To download a file in a new tab or window without disrupting the current page:

Using an Invisible Iframe:

This method creates an invisible iframe and assigns the download URL to its src attribute:

<iframe>
Copy after login

This triggers the download in the background. To ensure that the browser downloads non-renderable files (e.g., HTML, text), the server must set the file's MIME type to a nonsensical value like application/x-please-download-me or application/octet-stream.

Opening in a New Tab (jQuery):

To open the file in a new tab, use jQuery to set the link's target attribute to _blank and specify the file's URL in the href attribute:

$('a#someID').attr({
  target: '_blank',
  href: 'http://localhost/directory/file.pdf'
});
Copy after login

When the link is clicked, the file will be downloaded in a new tab or window, depending on the browser's settings.

The above is the detailed content of How Can I Download Files in a New Tab or Window Using JavaScript/jQuery Without Replacing the Current Page?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template