Home >Web Front-end >JS Tutorial >How to Download Files in a New Window or Tab Using JavaScript/jQuery?

How to Download Files in a New Window or Tab Using JavaScript/jQuery?

Barbara Streisand
Barbara StreisandOriginal
2024-12-29 13:08:19773browse

How to Download Files in a New Window or Tab Using JavaScript/jQuery?

Downloading Files in a Separate Window/Tab Using JavaScript/jQuery

In certain scenarios, it becomes necessary to initiate a file download manually without interfering with the current page content. Unlike using window.href, this process involves opening the download in a separate window or tab.

Using an Invisible iframe:

To achieve this, an invisible <iframe> can be utilized:

<iframe>

The <iframe>'s src attribute should be set to the file's URL. In order to force browsers to download certain file types (e.g., HTML or text), assign a nonsensical MIME type to the file on the server, such as application/x-please-download-me or application/octet-stream.

Using a New Tab/Window:

If the goal is to open the file in a new tab or window without downloading, set the target attribute of a link element to _blank:

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

Upon clicking, the file will open in the user's preferred choice of a new tab or window.

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

Statement:
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