This javascript is nice that it doesn't open a new window or tab.

window.location.assign(url);
Answer from mozgras on Stack Overflow
🌐
WebDeveloper.com
webdeveloper.com › community › 219294-open-and-close-javascript-window-to-download-a-file
Open and Close Javascript Window (to download a file)
Hidden iframe! That sounds great! How wold I do that? Many thanks! ... Just have an iframe with display:none set then literally just point your link at it (in the target="" attribute).
🌐
Plain English
plainenglish.io › home › blog › web development › 5 ways to download front-end files
5 Ways to Download Front-end Files
November 16, 2022 - Open. It is also impossible to download cross-domain files. After all, it is window.open, not window.download (window.download is an imaginary).
🌐
Super User
superuser.com › questions › 1823477 › chrome-wont-allow-download-of-file-opened-via-chrome-extensions-javascript-win
Chrome won't allow download of file opened via Chrome Extension's Javascript window.open(URL) - Super User
I have a Chrome extension which offers buttons, which when clicked perform a windows.open("url") command. This part works fine, and I get a new tab when clicked, with the correct URL. But Chrome won't let me download this file.
🌐
Spiceworks
community.spiceworks.com › spiceworks support
'Window.open' a html file, gets downloaded instead of opened - Spiceworks Support - Spiceworks Community
November 11, 2011 - Hi, I’m working on a plugin which opens a HTML file (a return form for devices). I’ve added the HTML as a file in the plugin, and made a small javascript which should open the page in a pop-up. function URLSeeker(document){ return plugin.contentUrl(document); } function init() { SPICEWORKS.app.inventory.group.item.addTool(‘other’,function(){ var returnFormURL =URLSeeker(‘form.html’) window.open(returnFormURL, ‘venster_naam’, ‘width=650,height=980’); return false }).update(‘Retour Form’...
🌐
MDN Web Docs
developer.mozilla.org › en-US › docs › Web › API › Window › open
Window: open() method - Web APIs | MDN
The open() method of the Window interface loads a specified resource into a new or existing browsing context (that is, a tab, a window, or an iframe) under a specified name.
Find elsewhere
🌐
Google Groups
groups.google.com › g › google-web-toolkit › c › Y9hnPFtySuU
How to download a file from server without browser opening new window?
Hi, I created a servlet that provides a downloadable file (from String content) by writing to the ServletOutputStream. On the client side, I trigger the file download by an Anchor with: Window.open(GWT.getModuleBaseURL() + "MyServlet", "_blank", ""); It works fine, BUT it seems to open a new browser window, which is somehow directly closed.
🌐
Vaadin
vaadin.com › forum › t › download-stream-file-resource-via-window-open-opening-new-app › 112313
Download (Stream/File Resource) via window.open() opening new App - Vaadin Forum
April 4, 2011 - Basically whats happening is instead of the browser opening a file dialog to download the file, another browser window opens with the Vaadin App main window (and its widgets) contained within it I suspect it might be related to the fact I’m running Vaadin embedded in an HTML div within an ...
🌐
Pixelscommander
pixelscommander.com › javascript › javascript-file-download-ignore-content-type
Better approach to download file in JavaScript
July 17, 2014 - Generally there are two file downloading techniques in HTML/JS: window.open and mouse click / tap on link. Both of this methods are not ideal. During investigation of the question some interesting solutions were found.
Top answer
1 of 4
110

You can achieve this using the download attribute for <a> elements. For example:

<a href="1251354216241621.txt" download="your-foo.txt">Download Your Foo</a>

This attribute indicates that the file should be downloaded (instead of displayed, if applicable) and specifies which filename should be used for the downloaded file.

Instead of using window.open() you could generate an invisible link with the download attribute and .click() it.

var str = "Name, Price\nApple, 2\nOrange, 3";
var uri = 'data:text/csv;charset=utf-8,' + str;

var downloadLink = document.createElement("a");
downloadLink.href = uri;
downloadLink.download = "data.csv";

document.body.appendChild(downloadLink);
downloadLink.click();
document.body.removeChild(downloadLink);

Unfortunately this isn't supported in all browsers, but adding it won't make things worse for other browsers: they'll continue to download the files with useless filenames. (This assumes that you're using a MIME type is that their browser attempts to download. If you're trying to let the user download an .html file instead of displaying it, this won't do you any good in unsupported browsers.)

2 of 4
28

That does not work in latest Chrome, I have modified that and the following code will work fine,

 $("#download_1").on('click', function() {
    var json_pre = '[{"Id":1,"UserName":"Sam Smith"},{"Id":2,"UserName":"Fred Frankly"},{"Id":1,"UserName":"Zachary Zupers"}]';
    var json = $.parseJSON(json_pre);
   
    var csv = JSON2CSV(json);
    var downloadLink = document.createElement("a");
    var blob = new Blob(["\ufeff", csv]);
    var url = URL.createObjectURL(blob);
    downloadLink.href = url;
    downloadLink.download = "data.csv";

    document.body.appendChild(downloadLink);
    downloadLink.click();
    document.body.removeChild(downloadLink);
});

So when you click on download_1 id button then it will create an invisible download link and click that. I have used another function to prepare js.

The JSON2CSV function is as follows:

function JSON2CSV(objArray) {
    var array = typeof objArray != 'object' ? JSON.parse(objArray) : objArray;
    var str = '';
    var line = '';

    for (var i = 0; i < array.length; i++) {
        var line = '';

        for (var index in array[i]) {
           line += array[i][index] + ',';
        }

        line = line.slice(0, -1);
        str += line + '\r\n';
    }
    return str;
}

Hope it will help others :)

Top answer
1 of 1
2

Intro

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.

javascript:fetch(window.location.href).then(resp => resp.blob()) .then(blob => { const url = window.URL.createObjectURL(blob); const a = document.createElement('a'); a.style.display = 'none'; a.href = url; a.download = prompt("Enter filename and extension (e.g. myImage.jpg):", window.location.href.split('\/').pop() === "" ? window.location.hostname + ".html" : window.location.href.split('\/').pop()); document.body.appendChild(a); if(a.download !== "null") { a.click(); alert('Your file ' + a.download + ' has downloaded!'); } window.URL.revokeObjectURL(url); }) .catch(() => alert('Could not download file.'));

Breakdown

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

fetch(window.location.href)
  .then(resp => resp.blob())
  .then(blob => {
    const url = window.URL.createObjectURL(blob);
    const a = document.createElement('a');
    a.style.display = 'none';
    a.href = url;
    a.download = prompt("Enter filename and extension (e.g. myImage.jpg):", window.location.href.split('\/').pop() === "" ? window.location.hostname + ".html" : window.location.href.split('\/').pop());
    document.body.appendChild(a);
    if(a.download !== "null")
    {
        a.click();
        alert('Your file ' + a.download + ' has downloaded!');
    }
    window.URL.revokeObjectURL(url);
  })
  .catch(() => alert('Could not download file.'));

1) Using the Fetch browser API

fetch(window.location.href)

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

.then(resp => resp.blob())
  .then(blob => {
    const url = window.URL.createObjectURL(blob);

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

3) Creating the anchor tag

const a = document.createElement('a');
a.style.display = 'none';
a.href = url;
a.download = prompt("Enter filename and extension (e.g. myImage.jpg):", window.location.href.split('\/').pop() === "" ? window.location.hostname + ".html" : window.location.href.split('\/').pop());

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

document.body.appendChild(a);
if(a.download !== "null")
{
    a.click();
    alert('Your file ' + a.download + ' has downloaded!');
}
window.URL.revokeObjectURL(url);
})
.catch(() => alert('Could not download file.'));

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.

🌐
Treehouse Blog
blog.teamtreehouse.com › learn-programmatically-opening-file-downloads-new-window-javascript
Learn How: Programmatically Open File Downloads in a New Window with JavaScript | Treehouse Blog
September 11, 2023 - You could put anything here. But you’ll see "_new" used in most places meaning new window. The target attribute is a reference to a window. All links with the same target will be opened up in that window. We could easily do something like "download" instead.
🌐
GitHub
github.com › OfficeDev › office-js › issues › 1145
window.open method does not provide the expected result · Issue #1145 · OfficeDev/office-js
October 31, 2019 - `function DownloadExcelTemplate() { $('#btnDownloadExcel').hide(); $('#btnDownloadingExcel').show(); $.ajax({ type: 'get', cache: false, url: '/api/Template/DownloadExcelTemplate', data: { templateId: templateId, userId: parseInt(localStorage.getItem("UserID")) }, contentType: 'application/json;charset=utf-8' }).done(function (res) { if (res !== null && res !== "") { setTimeout(function () { window.open(location.origin + res, '_blank'); }, 250); } else { app.showNotification('Error', 'File not found.'); } $('#btnDownloadExcel').show(); $('#btnDownloadingExcel').hide();
Author   Cata-ExF
🌐
GitHub
gist.github.com › jmcarp › 9291539
Forcing a file download in JavaScript · GitHub
Opening the image in same window rather than downloading. To force download your file, you have to set in http response header with 'Content-Disposition' property, for more info, you can visit this article https://blog.logrocket.com/programmatic-file-downloads-in-the-browser-9a5186298d5c/
🌐
Stack Overflow
stackoverflow.com › questions › 52072098 › how-to-download-multiple-files-with-window-open
How to download multiple files with window.open()?
It will open all 3 windows at same time. let test = [204, 205, 206]; let downLoadFileBaseUrl = '/host/Controller/DownloadDasFiles?paramId=' test.forEach(element => { let file = `${downLoadFileBaseUrl}+${element}`; window.open(file, '_blank', 'File :' + element + ',scrollbars=1,menubar=0,resizable=1,width=850,height=500'); });