[javascript] How to trigger a file download when clicking an HTML button or JavaScript

There is a difference between loading a file and downloading a file. The following html code loads a file:

<a href="http://www.fbi.gov/top-secret.pdf">loading on the same tab</a>

After clicking on this link, your current tab will be replaced with the pdf-file that can then be downloaded. On right-clicking on this link, you can choose the menu item save link as for downloading the file directly. If you wish to obtain a save as dialog on clicking on such a link, you might want to take the following code:

<a href="http://www.fbi.gov/top-secret.pdf?download=1">save as...</a>

Your browser will download this file immediately if you choose to use a download directory in your options. Otherwise, your browser will be offering a save as-dialog.

You can also choose a button for downloading:

<button type="submit" onclick="window.open('http://www.fbi.gov/top-secret.pdf?download=1')">
    save as...
</button>

If you wish to load the link on a new tab, you take

<a href="http://www.fbi.gov/top-secret.pdf" target="_blank">loading on a new tab</a>

A form element does not heed the directive ?download=1. It only heeds the directive target="_blank":

<form method="get" action="http://www.fbi.gov/top-secret.pdf" target="_blank">
    <button type="submit">loading on a new tab</button>
</form>

Examples related to javascript

need to add a class to an element How to make a variable accessible outside a function? Hide Signs that Meteor.js was Used How to create a showdown.js markdown extension Please help me convert this script to a simple image slider Highlight Anchor Links when user manually scrolls? Summing radio input values How to execute an action before close metro app WinJS javascript, for loop defines a dynamic variable name Getting all files in directory with ajax

Examples related to html

Embed ruby within URL : Middleman Blog Please help me convert this script to a simple image slider Generating a list of pages (not posts) without the index file Why there is this "clear" class before footer? Is it possible to change the content HTML5 alert messages? Getting all files in directory with ajax DevTools failed to load SourceMap: Could not load content for chrome-extension How to set width of mat-table column in angular? How to open a link in new tab using angular? ERROR Error: Uncaught (in promise), Cannot match any routes. URL Segment

Examples related to download

how to download file in react js How do I download a file with Angular2 or greater Unknown URL content://downloads/my_downloads python save image from url How to download a file using a Java REST service and a data stream How to download file in swift? Where can I download Eclipse Android bundle? How to download image from url android download pdf from url then open it with a pdf reader Flask Download a File