How to download the current page as a file / attachment using Javascript?

Active3 hr before
Viewed126 times

8 Answers


// in the current page, download the html source
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:attachment/text,' + encodeURI(document.documentElement.outerHTML); = '_blank'; = 'myFile.txt';;
load more v

I am aware of the hidden iFrame trick as mentioned here ( and in other answers.,Is there any way via Javascript to download the current page as a file, or is copying to the clipboard my only option?,How can I use Javascript to download the current page (IE: the current DOM, or some sub-set of it) as a file?, Why do some planets in Star Trek have a numeric designation while others have just a name?

Like in:

    <div id="hello">
    document.location = 
        'data:text/attachment;,' + //here is the trick
            //document.documentElement.innerHTML; //To Download Entire Html Source
load more v

JavaScript is best known for web page development but it is also used in a variety of non-browser environments. You can learn JavaScript from the ground up by following this JavaScript Tutorial and JavaScript Examples.,Difference between var and let in JavaScript,Convert a string to an integer in JavaScript,How do you run JavaScript script through the Terminal?

To trigger a file download on a button click we will use a custom function or HTML 5 download attribute.
Approach 1: Using Download attribute 
The download attribute simply uses an anchor tag to prepare the location of the file that needs to be downloaded. The name of the file can be set using the attribute value name, if not provided then the original filename will be used.

<a download="filename">
load more v

Note: although it supports the most recent browsers, there are a couple of trick that you need to know to provide full support.,In this article we are going to show you a couple of tricks to generate and download directly a file using pure Javascript., How to download a file to a server using JSCH (SFTP) in android June 26 2016 Java ,Make libraries, not the war. FileSaver.js implements the saveAs() FileSaver interface in browsers that do not natively support it.

The following simple function allow you to generate a download of a file directly in the browser without contact any server. It works on all HTML5 Ready browsers as it uses the download attribute of the <a> element:

function download(filename, text) {
   var element = document.createElement('a');
   element.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(text));
   element.setAttribute('download', filename); = 'none';


// Start file download.
download("hello.txt", "This is the content of my file :)");
load more v

I need to start download manually when $('a#someID').click();,But I cannot use window.href method, since it replaces the current page contents with the file you’re trying to download.,This method works only when you want to download an image file… and it does not need the use of JQuery.,You can load the image into a canvas element get the data URL of the canvas and open a new window with the data URL as the source.

Use an invisible Iframe. If the file type is not nonsensical then set it up to make it as such.

   target: '_blank',
   href: 'http://myhost/directorypath/yourdownloadedfile.exe'
load more v

read the contents and properties of files or even generate new data for files — File API,generate object URLs for binary data — URL API,The URL interface allows for creating special kinds of URLs called object URLs, which are used for representing blob objects or files in a very concise format. Here is what a typical object URL looks like:,File downloading is a core aspect of surfing the internet. Tons of files get downloaded from the internet every day ranging from binary files (like applications, images, videos, and audios) to files in plain text.

Here is what the CSV generation script could look like:

function squareImages({
   width = 1,
   height = width
} = {}) {
   return width / height === 1;

function collectionToCSV(keys = []) {
   return (collection = []) => {
      const headers = => `"${key}"`).join(',');
      const extractKeyValues = record => => `"${record[key]}"`).join(',');

      return collection.reduce((csv, record) => {
         return (`${csv}\n${extractKeyValues(record)}`).trim();
      }, headers);

const exportFields = ['id', 'author', 'filename', 'format', 'width', 'height'];

   .then(response => response.json())
   .then(data => data.filter(squareImages))
   .then(console.log, console.error);
load more v

An HTML5 input form element must be included in the webpage that renders in the client’s browser;,A JavaScript method must be coded to initiate the asynchronous Ajax based file upload;,Learn to optimize JavaScript,While they're both central to inter-application communication processes, it's important to understand the fundamental differences...

The following HTML5 tags provide the required components to add a file selector and an upload button to any web page:

<input id="fileupload" type="file" name="fileupload" />
<button id="upload-button" onclick="uploadFile()"> Upload </button>

The button kicks off a method named uploadFile(), which contains the JavaScript file upload logic.

async function uploadFile() {
    let formData = new FormData();           
    formData.append("file", fileupload.files[0]);
    await fetch('/upload.php', {
      method: "POST", 
      body: formData
    alert('The file has been uploaded successfully.');
load more v

This example, which uses PHP on the server side and JavaScript on the client side, demonstrates asynchronous uploading of a file.,© 2005-2021 Mozilla and individual contributors. Content is available under these licenses.,In this example, we're turning the element with the ID dropbox into our drop zone. This is done by adding listeners for the dragenter, dragover, and drop events.,TechnologiesTechnologies OverviewHTMLCSSJavaScriptGraphicsHTTPAPIsBrowser ExtensionsMathML

<input type="file" id="input" multiple>
load more v

Other "current-using" queries related to "How to download the current page as a file / attachment using Javascript?"