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

Asked
Active3 hr before
Viewed126 times

8 Answers

currentusing
90%

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

I am aware of the hidden iFrame trick as mentioned here (http://stackoverflow.com/questions/365777/starting-file-download-with-javascript) 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:

<html>
<head>
    <style>
    </style>
</head>
<body>
    <div id="hello">
        <span>world</span>
    </div>
<script>
(function(){
    document.location = 
        'data:text/attachment;,' + //here is the trick
        document.getElementById('hello').innerHTML;
            //document.documentElement.innerHTML; //To Download Entire Html Source
})();
</script>
</body>
</html>
load more v
72%

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.
Syntax 
 

<a download="filename">
load more v
65%

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);

   element.style.display = 'none';
   document.body.appendChild(element);

   element.click();

   document.body.removeChild(element);
}

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

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.

$('a#someID').attr({
   target: '_blank',
   href: 'http://myhost/directorypath/yourdownloadedfile.exe'
});
load more v
40%

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 = keys.map(key => `"${key}"`).join(',');
      const extractKeyValues = record => keys.map(key => `"${record[key]}"`).join(',');

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

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

fetch('https://picsum.photos/list')
   .then(response => response.json())
   .then(data => data.filter(squareImages))
   .then(collectionToCSV(exportFields))
   .then(console.log, console.error);
load more v
22%

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.

<script>
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.');
}
</script>
load more v
60%

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?"