youtube logo

5 Ways to Download Front-end Files

1. a label, 2. window.open, 3. location.href, 4. location. other properties, and 5. xmlhttprequest. what are the pros and cons of each method.

By Zard-x on November 16th, 2022

image

The file download involved in the front-end still has many application scenarios, so how many ways are there for the front-end file download? What are the advantages and disadvantages of each method? Let’s introduce them one by one.

File download is achieved through the download attribute of the a tag. This method is the simplest and the most commonly used method. Let’s first look at the sample code:

In the above example, we clicked download and found that we jumped to the homepage of Google, and did not actually download the file. Because a tag download can only download files of the same origin, if it is a cross-domain file, including pictures, audio and video and other media files, it is a preview and cannot be downloaded. The above code is to achieve file download directly by writing a tag, we can also achieve it through js, the code is as follows:

The effect is the same as the above, it jumps to Baidu’s homepage without downloading files. The focus here is the download attribute of a tag, which is new in HTML5. Its function is to specify the downloaded file name. If it is not specified, the downloaded file name will be determined according to the Content-Disposition of the requested content. If there is no Content-Disposition, then the last part of the requested URL will be used as the file name.

2. window.open

The above case of using a tag can also be achieved through window.open, the effect is the same, and the code is as follows:

The _blank here is the way to specify the opening. If not specified, it will be opened on the current page. Specifying _blank here means opening it on a new page. The download attribute of a tag can also be used, the code is as follows:

Of course, this method is also flawed. Compared with a tag, this method cannot download .html, .htm, .xml, .xhtml, and other files, because these files will be treated as HTML files, so they will be directly on the current page. Open. It is also impossible to download cross-domain files. After all, it is window.open, not window.download (window.download is an imaginary).

3. location.href

This method is the same as window.open(url), the code is as follows:

This method has all the defects of window.open, so it is not recommended to use it. It is only used as an understanding here, so I will not explain it too much.

4. location.? Other properties

Others here refer to the properties that can jump to the page, such as location.assign, location.replace, location.reload, etc. These properties can realize file download, the code is as follows:

The location.reload here is a bit special, its function is to reload the current page, but it can also accept a parameter, this parameter is the page to be jumped, so it can also achieve file download. Of course, like location.href, these methods have the same disadvantages, and also have their own characteristics of each attribute. This is only to expand knowledge and not to explain too much.

5. XMLHttpRequest

This method is what we often call ajax download, including Axios, fetch, etc. are the same, the code is as follows:

I won’t talk about the knowledge related to XMLHttpRequest here, only the part related to file download. The main logic here is that when our request is successful, we will get the response of the response body, this response is the content we want to download, and then we convert it into a blob object, and then create a url through URL.createObjectURL, and then File download is achieved through the download attribute of the a tag. There are two knowledge points here, one is the blob object, and the other is URL.createObjectURL.

Here is the definition of the blob object, from MDN :

The Blob object represents a blob, which is a file-like object of immutable, raw data; they can be read as text or binary data, or converted into a ReadableStream so its methods can be used for processing the data.Blobs can represent data that isn't necessarily in a JavaScript-native format. The File interface is based on Blob, inheriting blob functionality and expanding it to support files on the user's system.

The blob object is a new object in html5. Its function is to store binary data, such as pictures, videos, audio, etc. Its usage is as follows:

The main concern here is the type attribute. By default, the blob object has no type attribute, so the blob is an untyped blob, and the file will not be damaged, but it cannot be recognized normally.

5.2 URL.createObjectURL

The following is from MDN :

The URL.createObjectURL() static method creates a string containing a URL representing the object given in the parameter.The URL lifetime is tied to the document in the window on which it was created. The new object URL represents the specified File object or Blob object.

This method is used to create a url. Its function is to convert a blob object into a url. This url can be used to download files or preview files. The code is as follows:

It should be noted here that the life cycle of this url is bound to the document in the window that created it, that is to say, when our document is destroyed, the url will be invalid, so we need to destroy it at the right time, code show as below:

Back to the problem we just downloaded, we solved it through the blob object, but our type attribute is hard-coded. If the file type is determined, there is no problem, but if this interface is the interface for downloading files, Files can be of various types, what should we do with them? There is no correct answer here. The first is to negotiate with the interface provider. The negotiation scheme is uncertain. The second is to obtain the type of the file through the header of the response, which is also what we want to talk about:

Here we get the type through the header of the response, and then create the blob object, so that the file can be downloaded correctly. In fact, content-type may also be application/octet-stream. At this time, we need to obtain the type of the file through file-type. The following code uses file-type to get the type of the file:

The use of file-type can be referred to here.

There are so many solutions above, but in fact, it finally falls on a tag, so whether it is downloaded through the built-in behavior of the browser or downloaded through ajax, the final file download is the behavior of the browser.

Continue Learning

How to declare static constants in es6 classes, react: updating a value in state array.

How to update just one value in an array of objects in a state

How To Calculate The EMA Of A Stock With Python

The best free ai tool for image generation: not midjourney, 7 really good reasons not to use typescript, chatgpt vs. software development: will ai replace developers.

Stack Exchange Network

Stack Exchange network consists of 183 Q&A communities including Stack Overflow , the largest, most trusted online community for developers to learn, share their knowledge, and build their careers.

Super User is a question and answer site for computer enthusiasts and power users. It only takes a minute to sign up.

Q&A for work

Connect and share knowledge within a single location that is structured and easy to search.

Force a download via browser

I'm looking for a way to force a download on a URL you put in your browser (preferably your browser's address field but without hitting enter, so the URL doesn't get loaded first). This should work for any link, not just certain file types. Basically it should be the analog to right-clicking a link and choosing the "save as"-option.

My current "first" workaround is a bookmark with the following javascript code:

It will create an empty page with just a link to the site I was on while clicking on the bookmark. From there I can then use it with the right click and "save as" option. Works fine for all sorts of file eg. mp4 files, textfiles, htmlfiles etc.

However, this does not work all the time, currently I have the following problem(s):

if the browser has to "load" a large file before creating the link which take time with some large files. I have a current issue, where a PFD file does not get recognized as PDF and get parsed as text into the browser window which gets displayed sort of like this %PDF-1.5 %�50obj<>x��... my workarounds works, but it's not very performant if the file has several MB. (And because of the parsing saving the content of the browser window does not create a correct PDF file anymore)

with files that get stored locally (e.g. PDF files inside the Firefox PDF viewer). But PDF files are not that bad since the viewer gives me a download button.

My current solution does not work well for big files (as stated above). So I currently use my "second" workaround: I create a simple website file with just the link (I always use the same HTML-file just exchanging the link), I open the html which includes the link in the browser and then I right-click on it etc.

I wonder if there is a more elegant way to do that? I want to get rid of the necessity for my second workaround (to open my "manual" HTML file, update the link, and then go through the right-click, etc). Although I am happy about any workaround that saves time and can be accessed from within the browser (e.g. by a bookmark etc.) , I'd prefer solutions that can be implemented without browser addons. If an addon is necessary I would prefer open source.

Currently, my main browser is Firefox, but feel free to add additional solutions for other browser types as well.

Albin's user avatar

I was able to achieve a one-click bookmark that downloads the current browser url. I was able to test this in both Chrome and Firefox for both html files and images, and PDF files.

The code will first ask you what to name the file (including the file's extension) using the browser's prompt built in, you can also cancel the download at this point in time.

Here is the code that you can paste into the Location field of a newly created bookmark:

EDIT: For files hosted on Intranet use this bookmark. Now works for internet as well.

Here is the code on multiple lines so we can break it down

1) Using the Fetch browser API

In this bookmark, we are using the brower's built-in fetch API to download the file contents located at the url of the current tab's address bar.

2) Using a Blob

We construct a Blob from the response that we receive. This will allow us to download the file.

3) Creating the anchor tag

We create an anchor tag and here we have the option to ask the user to set the filename. It is important to do this so we can get the correct file extension. Note: If you would like to remove this prompt, you can set a.download to whatever you would like. For example: a.download = "downloaded_file";

However, by using a prompt we can allow the user to cancel the operation before it downloads.

4) Downloading the file and giving feedback with alerts

If a.download is a string that equals "null" (an actual string and not the type null), it means the user pressed cancel on the prompt, so we skip over automatically clicking our anchor tag.

At this point in the script, you can remove the alert lines if you don't want them to pop up.

iskyfire's user avatar

  • wow, this is a thorough answer. thanks a lot. on first tests it did not work with the files a have in mind. Apparently it handles the url/source differently from the right-click download (if you right-click on a link). Unless you have a quick fix, you want me to try please give me a while to give you better feedback. –  Albin Aug 9, 2020 at 15:53
  • What file types do you need to download? –  iskyfire Aug 9, 2020 at 15:55
  • This bookmark should work with files hosted on the web that do not require authentication. If you are trying to download files on websites that you need to sign in to access, we would need to change our approach. –  iskyfire Aug 9, 2020 at 16:07
  • It is not restricted to a certain file type, it's all sort of data including binary. For know I'm just trying to replicate the right-click-save-as function. –  Albin Aug 9, 2020 at 16:09
  • Are you able to post a sample link? –  iskyfire Aug 9, 2020 at 16:15

You must log in to answer this question.

Not the answer you're looking for browse other questions tagged firefox browser download ..

  • The Overflow Blog
  • How to scale a business-ready AI platform with watsonx: Q&A with IBM sponsored post
  • Will developers return to hostile offices?
  • Featured on Meta
  • We're rolling back the changes to the Acceptable Use Policy (AUP)
  • Seeking feedback on tag colors update

Hot Network Questions

  • How to render an image the exact way its displayed in the vrendered preview
  • How to calculate this improper integral?
  • Are stable isotopes ever used in pharmaceuticals?
  • Difference between 幺 and 么
  • Questions about categorial propositions
  • How does one get past unlucky work history streak?
  • How long should I stay in Ireland when granted entry without a visa and my passport stamped “Visa Warning Given”?
  • Ice is melted in the water
  • Resolving an apparent contradiction between Schwarzschild and ingoing Eddington-Finkelstein coordinates
  • How do I typeset RTL language phrases inside a document with mostly LTR text?
  • What does "everything" mean?
  • Make LaTeX directly recognize unicode symbol
  • If I cut out a square of drywall for access, should I tape the seams when I put it back?
  • Why is "John makes Bob looks short." wrong?
  • videos from non-linux partition don't play
  • What are these classic 80's action movies?
  • Is it possible in Mathematica to get a step-by-step evaluation of the following?
  • Is it common for community colleges in the US to have IRBs?
  • Film from the 1960s, like "She," that ends with a lost underground city being destroyed by an atom bomb
  • Ungolf the Wind
  • What are some roadblocks preventing a free trade agreement between the EU and the US?
  • How can I remove smoke from a bag of holding?
  • Supervisor refuses to be included as a co-author in PhD student papers?
  • Boiler *might* have caused water intrusion... who do I call?

window location assign download file

Your privacy

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy .

  • Skip to main content
  • Skip to search
  • Skip to select language
  • Sign up for free
  • English (US)

Location: assign() method

The Location.assign() method causes the window to load and display the document at the URL specified. After the navigation occurs, the user can navigate back to the page that called Location.assign() by pressing the "back" button.

If the assignment can't happen because of a security violation, a DOMException of the SECURITY_ERROR type is thrown. This happens if the origin of the script calling the method is different from the origin of the page originally described by the Location object, mostly when the script is hosted on a different domain.

If the provided URL is not valid, a DOMException of the SYNTAX_ERROR type is thrown.

A string containing the URL of the page to navigate to.

Return value

None ( undefined ).

Specifications

Browser compatibility.

BCD tables only load in the browser with JavaScript enabled. Enable JavaScript to view data.

  • The Location interface it belongs to.
  • Similar methods: Location.replace() and Location.reload() .

Advisory boards aren’t only for executives. Join the LogRocket Content Advisory Board today →

LogRocket blog logo

  • Product Management
  • Solve User-Reported Issues
  • Find Issues Faster
  • Optimize Conversion and Adoption
  • Start Monitoring for Free

Programmatically downloading files in the browser

window location assign download file

Editor’s note: This article was last updated by Ivan Garza on 3 May 2023 to revise content and include information about how to force a browser to download a file.

Programmatically Downloading Files In The Browser

File downloading is a core aspect of the things we do on the internet. Tons of files get downloaded from the internet every day — from binary files like images, videos, and audio files, to plain text files, application files, and much more. Because of the importance of downloading files from the internet, it’s important to know how these files are downloaded, as well as the different methods for doing so.

In this article, I will demonstrate how to download files from the internet, both by enforcing the download from the website, as well as with a manual click. After that, we will go over content generation in various forms, how to download generated content, and understanding the download attribute. Lastly, we will go over the usage of blobs and object URLs:

Jump ahead :

How to fetch a file from a client

Enforcing file download, how to programmatically download a file in html.

  • Example 1: CSV generation from JSON array
  • Example 2: Image pixel manipulation using the Canvas API

Obtaining blobs

Reading blob content, object urls, creating and releasing object urls, using object urls, downloading generated content.

Traditionally, the file to be downloaded is first requested from a server by a client ,  such as a user’s web browser. The server then returns a response containing the contents of the file, as well as some instructional headers specifying how the client should download the file:

Schematic Of Client-Server Communication In Fetching A File Via HTTP

In this diagram, the green line shows the flow of the request from the client to the server over HTTP. The orange line shows the flow of the response from the server back to the client.

Though the diagram indicates the communication flow, it does not explicitly show what the request from the client looks like or what the response from the server looks like either. Here is what the response from the server could possibly look like:

Sample HTTP Response For A GIF Image 

In this response, the server simply serves the raw contents of the resource (represented with the final two rows of asterisks —  * ), which will be received by the client.

The response also contains headers that give the client some information about the nature of the contents that it receives. For this example response, the Content-Type and Content-Length headers provide that kind of information.

Given the example HTTP response from above, our web browser client would simply display or render the GIF image instead of downloading. For the purposes of this writing, what we would actually want is for the GIF or image to be downloaded instead of displayed. For this, an extra header will be needed to tell the client to automatically download the contents of the file.

To inform the client that the contents of the resource are not meant to be displayed, the server must include an additional header in the response. The Content-Disposition header is the right header for specifying this kind of information.

The Content-Disposition header was originally intended for mail user-agents , because emails are multipart documents that may contain several file attachments. However, it can be interpreted by several HTTP clients, including web browsers. This header provides information on the disposition type and disposition parameters.

The disposition type is usually one of the following:

  • Inline  : The body part is intended to be displayed automatically when the message content is displayed
  • Attachment :  The body part is separate from the main contents of the message and should not be displayed automatically except when prompted by the user

The disposition parameters are additional parameters that specify information about the body part or file, such as filename, creation date, modification date, read date, size, etc.

Here is what the HTTP response for the GIF image should look like to enforce file download:

The Asterisks In This Sample HTTP Response Represent The Binary Content Of The Image

Now the server enforces a download of the GIF image. Most HTTP clients will prompt the user to download the resource contents when they receive a response from a server like the one above.

Let’s say you have the URL to a downloadable resource. When you try accessing that URL on your web browser, it prompts you to download the resource file  —  whatever the file is.

window location assign download file

Over 200k developers use LogRocket to create better digital experiences

window location assign download file

The scenario described above is not feasible in web applications. For web apps, the desired behavior would be more akin to  downloading a file in response to a user interaction. For example, the user clicking a button that reads “Download.”

Achieving such a behavior in the browser is possible with HTML anchor elements: <a></a> . Anchor elements are useful for adding hyperlinks to other resources and documents directly from an HTML file. The URL of the linked resource is specified in the href attribute of the anchor element.

Here is an example of a conventional HTML anchor element linking to a PDF document:

Example Of A Basic HTML Anchor Element

The download attribute

In HTML 5, a new download attribute was added to the anchor element. The download attribute is used to inform the browser to download the URL instead of navigating to it  —  hence, a prompt shows up, requesting that the user saves the file.

The download attribute can be given a valid filename as its value. However, the user can still modify the filename in the save prompt that pops up.

There are a few noteworthy facts about the behavior of the download attribute:

  • In compliance with the same-origin policy, this attribute only works for same-origin URLs. So, it cannot be used to download resources served from a different origin
  • Besides HTTP(s) URLs, it also supports blob: and data: URLs , which makes it very useful for downloading contents generated programmatically with JavaScript
  • For URLs with an HTTP Content-Disposition header that specifies a filename,  the header filename has a higher priority than the value of the download attribute

Here is the updated HTML anchor element for downloading the PDF document:

HTML Anchor Element (<a srcset=

Programmatic content generation

With the advent of HTML5 and new Web APIs, it has become possible to do a lot of complex tasks in the browser using JavaScript without ever having to communicate with a server.

There are now Web APIs that can be used to programmatically:

  • Draw and manipulate images or video frames on a canvas  —  Canvas API
  • Read the contents and properties of files or even generate new data for files  —  File API
  • Generate object URLs for binary data  —  URL API

In this section, we will examine how we can programmatically generate content using Web APIs on the browser. Let’s consider two common examples.

Example 1 : CSV generation from JSON array

In this example, we will use the Fetch API to asynchronously fetch JSON data from a web service and transform the data to form a string of comma-separated values that can be written to a CSV file. Here is a breakdown of what we are about to do:

  • Fetch an array collection of JSON objects from an API
  • Extract selected fields from each item in the array
  • Reformat the extracted data as CSV

Here is what the CSV generation script can look like:

Here we are fetching a collection of photos from the Picsum Photos API . We are using the global fetch() function provided by the Fetch API, filtering the collection, and converting the collection array to a CSV string. The code snippet simply logs the resulting CSV string to the console.

First, we define a squareImages filter function for filtering images in the collection with equal width and height.

Next, we define a collectionToCSV higher-order function. This takes an array of keys and returns a function that takes an array collection of objects and converts it to a CSV string, extracting only the specified keys from each object.

Finally, we specify the fields we want to extract from each photo object in the collection in the exportFields array.

Here is what the output could look like on the console:

Output Of The HIgher Order Function On The Console

Example 2 :  Image pixel manipulation using the Canvas API

In this example, we will use the Canvas API to manipulate the pixels of an image, making it appear in grayscale. Here is a breakdown of what we are about to do:

  • Set the canvas dimensions based on the image
  • Draw the image on a canvas
  • Extract and transform the image pixels on the canvas to grayscale
  • Redraw the grayscale pixels on the canvas

Let’s say we have a markup that looks like this:

<div id=”image-wrapper”> <canvas></canvas> <img src=”https://example.com/imgs/random.jpg” alt=”Random Image”> </div>

Below is a comparison between an actual image and the corresponding grayscale canvas image:

Comparing An Actual Image With Its Grayscale Image

Blobs and object URLs

Before we learn how we can download content generated programmatically in the browser, let’s look at a special kind of object interface called Blob , which has already been implemented by most of the major web browsers.

Blobs are objects that are used to represent raw immutable data. Blob objects store information about the type and size of the data they contain, making them very useful for storing and working file contents on the browser. In fact, the File object is a special extension of the Blob interface.

Blob objects can be obtained from a few different sources:

  • Blobs can be created from non-blob data using the Blob constructor
  • Blobs can be sliced from an already existing blob object using the Blob.slice() method
  • Blobs can be generated from Fetch API responses or other Web API interfaces

Here are some code samples for the aforementioned blob object sources:

It is one thing to obtain a blob object and another thing altogether to work with it. One thing you want to be able to do is to read the contents of the blob. That sounds like a good opportunity to use a FileReader object.

A FileReader object provides some very helpful methods for asynchronously reading the contents of blob objects or files in different ways. The FileReader interface has pretty good browser support. At the time of writing, FileReader supports reading blob data as follows:

  • as text  —  FileReader.readAsText()
  • as binary string  —  FileReader.readAsBinaryString()
  • as base64 data URL  —  FileReader.readAsDataURL()
  • as array buffer  —  FileReader.readAsArrayBuffer()

Building on the Fetch API example we had before, we can use a FileReader object to read the blob as follows:

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:

The URL.createObjectURL() static method makes it possible to create an object URL that represents a blob object or file. It takes a blob object as its argument and returns a DOMString , which is the URL representing the passed blob object. Here is what it looks like:

It is important to note that this method will always return a new object URL each time it is called, even if it is called with the same blob object.

Whenever an object URL is created, it stays around for the lifetime of the document on which it was created. Usually, the browser will release all object URLs when the document is being unloaded. However, it is important that you release object URLs whenever they are no longer needed in order to improve performance and minimize memory usage.

The URL.revokeObjectURL() static method can be used to release an object URL. It takes the object URL to be released as its argument. Here is what it looks like:

Object URLs can be used wherever a URL can be supplied programmatically. For example:

  • They can be used to load files that can be displayed or embedded in the browser, such as images, videos, audios, PDFs, etc.,  for example, by setting the src property of an Image element
  • They can be used as the href attribute of an <a></a> element, making it possible to download content that was extracted or generated programmatically

So far, we have looked at how we can download files that are served from a server and sent to the client over HTTP , which is essentially the traditional flow. We have also seen how we can programmatically extract or generate contents in the browser using Web APIs.

In this section, we will examine how we can download programmatically generated contents in the browser, leveraging all we have learned from the beginning of the article and what we already know about blobs and object URLs.

Creating the download link

First, let’s say we have a blob object by some means. We want to create a helper function that allows us to create a download link ( <a></a> element) that can be clicked in order to download the contents of the blob, just like a regular file download.

The logic of our helper function can be broken down as follows:

  • Create an object URL for the blob object
  • Create an anchor element ( <a></a> )
  • Set the href attribute of the anchor element to the created object URL
  • Set the download attribute to the filename of the file to be downloaded. This forces the anchor element to trigger a file download when it is clicked
  • If the link is for a one-off download, release the object URL after the anchor element has been clicked

Here is what an implementation of this helper function will look like:

Notice that the helper function contains a function call in line 31 that is commented out. This function may trigger an automatic download if we wanted to force the download of the file as soon as you access the website. In order to force the file download to happen automatically, uncomment line 31 from the script above to achieve that.

Also notice that the helper function takes a filename as its second argument, which is very useful for setting the default filename for the downloaded file.

The helper function returns a reference to the created anchor element ( <a></a> ), which is very useful if you want to attach it to the DOM or use it in some other way.

Here is a simple example:

Now that we have our download helper function in place, we can revisit our previous examples and modify them to trigger a download for the generated contents.

1. CSV generation from JSON array

We will update the final promise .then handler to create a download link for the generated CSV string and automatically click it to trigger a file download using the downloadBlob helper function we created in the previous section.

Here is what the modification should look like:

Here we updated the final promise .then handler as follows. First, we create a new blob object for the CSV string, also setting the correct type using:

Then, we call the downloadBlob helper function to trigger an automatic download for the CSV file, specifying the default filename as “photos.csv” . Next, we move the promise rejection handler to a separate .catch() block:

Here is a working and more advanced example of this application on Codepen :

See the Pen JSON Collection to CSV by Glad Chinda ( @gladchinda ) on CodePen .

2. Image pixel manipulation

We will add some code to the end of the load event listener of the img object, to allow us:

  • Create a blob object for the grayscale image in the canvas using the Canvas.toBlob() method
  • Then, we’ll create a download link for the blob object using our downloadBlob helper function from before
  • Finally, we’ll append the download link to the DOM

Here is what the update should look like:

Here is a working example of this application on Codepen :

See the Pen Image Pixel Manipulation — Grayscale by Glad Chinda ( @gladchinda ) on CodePen .

We’ve covered a lot of ground in this tutorial. We explored the basics of the client-server relationship, and the way the former requests a file from the latter, to download files using HTML. We also generated our own content, and explored blobs and object URLs.

All in all, the importance of downloading files through the internet browser or a web application will remain a central topic of web development in general. This is why it is crucial to understand the different methods of download.

Share this:

  • Click to share on Twitter (Opens in new window)
  • Click to share on Reddit (Opens in new window)
  • Click to share on LinkedIn (Opens in new window)
  • Click to share on Facebook (Opens in new window)

window location assign download file

Stop guessing about your digital experience with LogRocket

Recent posts:.

window location assign download file

Using ElectricSQL to build a local-first application

ElectricSQL is a cool piece of software with immense potential. It gives developers the ability to build a true local-first application.

window location assign download file

Using Rust and Leptos to build beautiful, declarative UIs

Leptos is an amazing Rust web frontend framework that makes it easier to build scalable, performant apps with beautiful, declarative UIs.

window location assign download file

5 best JavaScript multidimensional array libraries

Learn more about the 5 best JavaScript libraries for dealing with multidimensional arrays, such as ndarray, math.js, and NumJs.

window location assign download file

Leader Spotlight: Leading by experience with Dom Scandinaro

We spoke with Dom about his approach to balancing innovation with handling tech debt and to learn how he stays current with technology.

window location assign download file

5 Replies to "Programmatically downloading files in the browser"

This is so great yet practical

Awesome article — this technique is total magic.

Hello. Great article! One comment though: in the function `downloadBlob` you declare a `clickHandler` that gets a value of an arrow function, which uses the `this` keyword. Since arrow functions do not have `this`, and you use `this` in a `setTimeout` callback function — it ends up being `undefined`, which throws when you perform the `.` operator on it (to call the `removeEventListener` method). Thanks for the article! Eran

Hi Eran, thanks for pointing that out. That was an error on my part.

The `clickHandler` function is supposed to be a regular JS function as opposed to an arrow function — that way, it would have the correct `this` binding internally (the target element) when it is eventually used as an event listener callback. If you notice in the subsequent Codepen snippets, you’d observe that the `clickHandler` function was defined as a regular function instead of as an arrow function.

Thanks again for spotting that out.

How to Specify Where Files Are Downloaded

By default, Chrome, Firefox and Microsoft Edge download files to the Downloads folder located at  %USERPROFILE%\Downloads . USERPROFILE is a variable that refers to the logged in user's profile directory on the Windows computer, e.g. the path may look like  C:\Users\YourUserName\Downloads . However, you may change download folder location in your favorite browser or change the location of the Downloads folder in Windows. 

How to change the location of the Downloads folder in Windows 10

How to specify where files are downloaded in google chrome, how to specify where files are downloaded in mozilla firefox, how to specify where files are downloaded in microsoft edge.

To change the location of the Downloads folder in Windows:

  • Right-click  Start  button, then select  File Explorer .

window location assign download file

2. Right-click the  Downloads  location at the left pane, then select Properties .

window location assign download file

3. Navigate to  Location  tab, click the  Move  button, then select the folder where the files will be downloaded and click  Select Folder.

4. Click OK  to apply changes. 

window location assign download file

WARNING!  Changing the location of the  Downloads  folder in Windows will affect all programs.

In Chrome, you may change the download folder location or make Chrome ask you every time where to download a file.

How to change default download folder location

To select a different download folder location:

  • Click the Chrome menu button (three horizontal bars) at the top right, then select  Settings .

window location assign download file

2. Click  Advanced  link at the bottom of the  Settings  page

3. In the  Downloads  section, click the  Change  button, then select the folder where the files will be downloaded and click  OK .  

window location assign download file

You can now see the path to the selected folder below the  Location . 

How to make Chrome ask you every time where to download a file

If you want Chrome to ask you every time about download folder location, follow these steps:

3. In the  Downloads  section, turn on the  Ask where to save each file before downloading  toggle.

How to find the files downloaded earlier in Chrome

Once the file is downloaded, you can see it at the bottom of the browser window. If you want to open the file you’ve downloaded earlier, press  Ctrl + J  or type  chrome://downloads  in the Chrome address line.  Downloads  list is displayed. 

window location assign download file

The files are grouped by the date they were downloaded. Click the file name to open it. You may also quickly browse to the folder containing the file. Simply click  Show in folder  link below the file name. 

In Firefox, you may change download folder location or make Firefox to ask you every time where to download a file.

  • Click the Firefox menu button (three horizontal bars) at the top right, then select  Options .

window location assign download file

2. Under  General > Downloads , click the  Browse  button, then select the folder where the files will be downloaded and click  Select Folder .  

window location assign download file

3. You can now see the path to the selected folder in the  Save files  box. 

How to make Firefox ask you every time where to download a file

If you want Firefox to ask you every time about download folder location, follow these steps:

2. Under  General > Downloads , select the  Always ask you where to save files.

window location assign download file

How to find the files downloaded in Firefox

 Once you’ve clicked the  Download  button, Firefox asks what it should do with the file – open or download it. Please select  Save  to download the file. 

window location assign download file

If you’ve chosen to use the default download location, the file will be saved in the selected folder. If you’ve chosen to select a download location each time, you would be able to select the desired folder.

You may reach all files downloaded during the current browser session by clicking the arrow icon at the top. You may also quickly browse to the folder containing the downloaded file. Simply click the folder icon next to the file name.

window location assign download file

If you want to open the file you’ve downloaded earlier, press  Ctrl + J.  Downloads tab of the  Library  pop-up list is displayed. The files are grouped by the date they were downloaded. Click the file name to open it or click the folder icon to browse to the folder containing the file. 

window location assign download file

In Edge, you may change download folder location or make Edge ask you every time where to download a file.

How to change default download folder location in Edge 

  • Click the Edge menu button (three horizontal dots) at the top right, select  Settings , and then click  View Advanced Settings .

window location assign download file

2. Under  Downloads , click the  Change  button, then select the folder where the files will be downloaded and click  Select Folder. 

window location assign download file

You can now see the path to the selected folder below  Save download files to. 

How to make Edge ask you every time where to download a file

If you want Edge to ask you every time about download folder location, follow these steps:

  • Click the Edge menu button (three horizontal dots) at the top right, select  Settings , and then click  View Advanced Settings .

2. Under  Downloads , turn on the  Ask me what to do with each download  toggle.

How to find the files downloaded in Edge

Once the file is downloaded, you can see the notification at the bottom of the browser window. You can open the file or the folder containing it. 

window location assign download file

The files are grouped by the date they were downloaded. Click the file name to open it. You may also quickly open the  Downloads  folder. Simply click  Open folder  link above the file list. 

The article was prepared by TaxDome team. TaxDome is an all-in-one platform for tax, bookkeeping, and accounting firms. The platform is equipped with useful tools that optimize the accountant’s work processes: client portal , tax organizers , and more.

# window.location Cheatsheet

Looking for a site's URL information, then the window.location object is for you! Use its properties to get information on the current page address or use its methods to do some page redirect or refresh 💫

https://www.samanthaming.com/tidbits/?filter=JS#2
  • Difference between host vs hostname
  • How to change URL properties
  • window.location vs location
  • window.location.toString
  • assign vs replace
  • replace vs assign vs href
  • Scratch your own itch 👍
  • Community Input

# window.location Properties

# difference between host vs hostname.

In my above example, you will notice that host and hostname returns the value. So why do these properties. Well, it has do with the port number. Let's take a look.

URL without Port

https://www.samanthaming.com

URL with Port

https://www.samanthaming.com:8080

So host will include the port number, whereas hostname will only return the host name.

# How to change URL properties

Not only can you call these location properties to retrieve the URL information. You can use it to set new properties and change the URL. Let's see what I mean.

Here's the complete list of properties that you can change:

The only property you can't set is window.location.origin . This property is read-only.

# Location Object

The window.location returns a Location object. Which gives you information about the current location of the page. But you can also access the Location object in several ways.

The reason we can do this is because these are global variables in our browser.

window location assign download file

# window.location vs location

All 4 of these properties point at the same Location object. I personally prefer window.location and would actually avoid using location . Mainly because location reads more like a generic term and someone might accidentally name their variable that, which would override the global variable. Take for example:

I think that most developer is aware that window is a global variable. So you're less likely to cause confusion. To be honest, I had no idea location was a global variable until I wrote this post 😅. So my recommendation is to be more explicit and use window.location instead 👍

Here's my personal order of preference:

Of course, this is just my preference. You're the expert of your codebase, there is no best way, the best way is always the one that works best for you and your team 🤓

# window.location Methods

# window.location.tostring.

This method returns the USVString of the URL. It is a read-only version of Location.href

In other words, you can use it to get the href value from the

on this 😊. But I did find a performance test on the difference.

JSPerf: Location toString vs Location href

One thing I want to note about these speed tests is that it is browser specific. Different browser and versions will render different outcome. I'm using Chrome, so the href came out faster then the rest. So that's one I'll use. Also I think it reads more explicit then toString() . It is very obvious that href will provide the URL whereas toString seems like something it being converted to a string 😅

# assign vs replace

Both of these methods will help you redirect or navigate to another URL. The difference is assign will save your current page in history, so your user can use the "back" button to navigate to it. Whereas with replace method, it doesn't save it. Confused? No problem, I was too. Let's walk through an example.

Current Page

I just need to emphasize the "current page" in the definition. It is the page right before you call assign or replace .

# How to Do a Page Redirect

By now, you know we can change the properties of the window.location by assigning a value using = . Similarly, there are methods we can access to do some actions. So in regards to "how to redirect to another page", well there are 3 ways.

# replace vs assign vs href

All three does redirect, the difference has to do with browser history. href and assign are the same here. It will save your current page in history, whereas replace won't. So if you prefer creating an experience where the navigation can't press back to the originating page, then use replace 👍

So the question now is href vs assign . I guess this will come to personal preference. I like the assign better because it's a method so it feels like I'm performing some action. Also there's an added bonus of it being easier to test. I've been writing a lot of Jest tests, so by using a method, it makes it way easier to mock.

But for that that are rooting for href to do a page redirect. I found a performance test and running in my version of Chrome, it was faster. Again performance test ranges with browser and different versions, it may be faster now, but perhaps in future browsers, the places might be swapped.

JSPerf: href vs assign

# Scratch your own itch 👍

Okay, a bit of a tangent and give you a glimpse of how this cheatsheet came to be. I was googling how to redirect to another page and encountered the window.location object. Sometimes I feel a developer is a journalist or detective - there's a lot of digging and combing through multiple sources for you to gather all the information available. Honestly, I was overwhelmed with the materials out there, they all covered different pieces, but I just wanted a single source. I couldn't find much, so I thought, I'll cover this in a tidbit cheatsheet! Scratch your own itch I always say 👍

# Community Input

: This is awesome, I’ve used window.location.href in the past, but didn’t realise how simple it is to access sections of the URL!

If you want to see a live-action of what James is talking about, check out the table of content at the top of this article. Click on it and it will scroll down to the specific section of the page.

# Resources

  • Share to Twitter Twitter
  • Share to Facebook Facebook
  • Share to LinkedIn LinkedIn
  • Share to Reddit Reddit
  • Share to Hacker News Hacker News
  • Email Email

Related Tidbits

Console.table to display data, colorful console message, window.location cheatsheet, fresh tidbits.

Code snippet on HTML abbr Tag

HTML abbr Tag

Code snippet on How to Pad a String with padStart and padEnd in JavaScript

How to Pad a String with padStart and padEnd in JavaScript

Code snippet on Avoid Empty Class in Vue with Null

Avoid Empty Class in Vue with Null

Code snippet on Fix Text Overlap with CSS white-space

Fix Text Overlap with CSS white-space

Code snippet on How to Check if Object is Empty in JavaScript

How to Check if Object is Empty in JavaScript

IMAGES

  1. JavaScript

    window location assign download file

  2. Sự khác biệt giữa window.location.assign () và window.location.replace ()?

    window location assign download file

  3. Difference between window.location.href and window.location.assign in JavaScript

    window location assign download file

  4. window.location Cheatsheet

    window location assign download file

  5. Compare location.href, location.replace, location.assign

    window location assign download file

  6. Window.location 用法详解

    window location assign download file

VIDEO

  1. File edges on window tint #windowtint

  2. How to change what program opens a file in windows

  3. Recommendation: What window manager should I start with?

  4. Learn JavaScript In Arabic 2021

  5. How to change default location/Desktop/Download/Documents/Pictures

  6. Windows 11 Home : How to set Default App to open .dqy Files

COMMENTS

  1. How Can You Find Your Recently Downloaded Files?

    To find recently downloaded files on your PC, click Start on the Windows tool bar, click on My Documents and then open the Downloads folder. The downloaded files are usually stored in the Downloads folder by default unless you save them to ...

  2. How Do You Open JPEG Files in Windows?

    Windows has a built-in image viewer called Windows Photo Viewer that allows users to view JPEG files; to open a JPEG file in Windows Photo Viewer, double-click on it and the image is displayed. Alternatively, choose a third-party applicatio...

  3. What Is a Web Address?

    A Web address, or URL, is an Internet address that denotes the location of a specific webpage, file or document on the World Wide Web. URL is a short for the term “uniform resource locator.” Every page or file located on the Web is assigned...

  4. Easiest way to open a download window without navigating away

    The best working solution to open a file download pop-up in JavaScript is to use a HTML link element, with no need to append the link element to

  5. 5 Ways to Download Front-end Files

    a label, 2. window.open, 3. location.href, 4. location.? Other ... location.assign, location.replace, location.reload, etc. These

  6. Force a download via browser

    ... download file.'));. Breakdown. Here is the code on multiple lines so we can break it down fetch(window.location.href) .then(resp => resp.blob

  7. Modifying file name during download using window.location

    Change file name when using window.location to download, Can I rename a file on download with a useful name based on other page elements?

  8. Location: assign() method

    The Location.assign() method causes the window to load and display the document at the URL specified. After the navigation occurs

  9. How to Download a File Using JavaScript/jQuery?

    To do this, simply use the “location.href” property of the “window” object and set it equal to the path of the file on the server, which will be downloaded on

  10. Programmatically downloading files in the browser

    In this article, we learn how to programmatically download files in HTML, and the importance of blobs and object URLs in file downloads.

  11. Установка имени файла Blob в JavaScript

    ... window.location.assign(url); }. Выполнение этого кода приводит к тому ... При таком подходе файл будет скачан с установленным именем my-download.

  12. Can I redirect to a page after a download?

    window.location.href = url_to_download_file_method;. I want to redirect to another page after the download is triggered. Is it possible?

  13. How to Specify Where Files Are Downloaded

    By default, Chrome, Firefox and Microsoft Edge download files to the Downloads folder located at %USERPROFILE%\Downloads. USERPROFILE is a

  14. window.location Cheatsheet

    The window.location object can be used to get information on the current page address (URL). You can also use its method to do a page redirect or refresh...