Change HTML downloadlink into downloadbutton through JavaScript - javascript

I'm trying to create a function where I can generate a blob .json file, which I then want to download.
I've checked around and found one way to do it.
function download_rapport(){
var data = geojson.features.map(function(row) { return row.properties; });
var json = JSON.stringify(data);
var blob = new Blob([json], {type: "application/json"});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.download = "backup.json";
a.href = url;
a.textContent = "Download backup.json";
document.getElementById('content_test').innerHTML = a.outerHTML;
// 'çontent_test' is a <div>
};
This works pretty well, however, this method uses a link to download. I would prefer to use a button, because it fits better with the rest of my application.
I used multiple methods to try and get a download button, but I always end up with a button that sends me to a new page with the data that I need shown as a string.
Is there a way to change my function so that it generates a downloadbutton instead of a downloadlink?
EDIT:
I've edited my code a bit with help from Midas. However, when I alter the data in my var json and try to download the "new" file, it will always download the "first" var json.
What I would like, is to be able to alter the var json data, and always download the "latest" version of it.
window.onload = function testreer() {
var data = geojson.features.map(function(row) { return row.properties; });
var json = JSON.stringify(data);
var blob = new Blob([json], {type: "application/json"});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
var b = document.createElement('button');
a.download = blob;
a.href = url;
b.innerText = 'Download';
document.getElementById('content_test').appendChild(b);
b.appendChild(a);
b.addEventListener('click', function() {
a.click();
});
}

Try this I have append a button in a link if that what you want.
function download_rapport(){
var data = geojson.features.map(function(row) { return row.properties; });
var json = JSON.stringify(data);
var blob = new Blob([json], {type: "application/json"});
var url = URL.createObjectURL(blob);
var a = document.createElement('a');
a.download = "backup.json";
a.href = url;
// 'çontent_test' is a <div>
var btn = document.createElement('button');
btn.value="download";
btn.innerHTML = "Download JSON";
a.appendChild(btn);
document.getElementById('content_test').innerHTML = a.outerHTML;
};

You can convert it it a button if you like
replace
document.createElement('a');
with
document.createElement("BUTTON");

I decided to give up on changing the link to a button. Instead, I will use CSS to style the link as a button. After checking around I found out that, although it is possible to change a link to a button, it is way faster to just use CSS to style it.
I edited my code a tiny bit by adding a.id = "downloadLink" to give the generated <a> an ID. This ID is then styled in my CSS file.
var a = document.createElement('a');
a.download = "backup.json";
a.href = url;
a.id = "downloadLink";
a.textContent = "Download backup.json";

Since a button has no href attribute like an a tag, you have to assign the desired action to the onclick event on the fly. An example is as follows:
window.onload = function()
{
var url = 'http://lipsum.com';
var btn = document.createElement('button');
btn.innerText = 'Download';
document.getElementById('content_test').appendChild(btn);
btn.addEventListener('click', function(){
window.location.href = url;
});
}
<div id="content_test"></div>
Edit:
Since the file is not coming from a server, you can create both the a tag and the button tag, triggering the link programmatically when the button is clicked:
window.onload = function() {
var url = 'http://lorempixel.com/400/300/technics/';
var a = document.createElement('a');
var b = document.createElement('button');
a.download = 'technics.jpg';
a.href = url;
b.innerText = 'Download';
document.getElementById('content_test').appendChild(b);
b.appendChild(a);
b.addEventListener('click', function() {
a.click();
});
}
<div id="content_test"></div>
However, In normal circumstances you would set Content-Disposition: attachment on the server side, to tell the browser that the file is to be downloaded.

Related

Cant write a textbox value to a .text file [duplicate]

I want to Write Data to existing file using JavaScript.
I don't want to print it on console.
I want to Actually Write data to abc.txt.
I read many answered question but every where they are printing on console.
at some place they have given code but its not working.
So please can any one help me How to actually write data to File.
I referred the code but its not working:
its giving error:
Uncaught TypeError: Illegal constructor
on chrome and
SecurityError: The operation is insecure.
on Mozilla
var f = "sometextfile.txt";
writeTextFile(f, "Spoon")
writeTextFile(f, "Cheese monkey")
writeTextFile(f, "Onion")
function writeTextFile(afilename, output)
{
var txtFile =new File(afilename);
txtFile.writeln(output);
txtFile.close();
}
So can we actually write data to file using only Javascript or NOT?
You can create files in browser using Blob and URL.createObjectURL. All recent browsers support this.
You can not directly save the file you create, since that would cause massive security problems, but you can provide it as a download link for the user. You can suggest a file name via the download attribute of the link, in browsers that support the download attribute. As with any other download, the user downloading the file will have the final say on the file name though.
var textFile = null,
makeTextFile = function (text) {
var data = new Blob([text], {type: 'text/plain'});
// If we are replacing a previously generated file we need to
// manually revoke the object URL to avoid memory leaks.
if (textFile !== null) {
window.URL.revokeObjectURL(textFile);
}
textFile = window.URL.createObjectURL(data);
// returns a URL you can use as a href
return textFile;
};
Here's an example that uses this technique to save arbitrary text from a textarea.
If you want to immediately initiate the download instead of requiring the user to click on a link, you can use mouse events to simulate a mouse click on the link as Lifecube's answer did. I've created an updated example that uses this technique.
var create = document.getElementById('create'),
textbox = document.getElementById('textbox');
create.addEventListener('click', function () {
var link = document.createElement('a');
link.setAttribute('download', 'info.txt');
link.href = makeTextFile(textbox.value);
document.body.appendChild(link);
// wait for the link to be added to the document
window.requestAnimationFrame(function () {
var event = new MouseEvent('click');
link.dispatchEvent(event);
document.body.removeChild(link);
});
}, false);
Some suggestions for this -
If you are trying to write a file on client machine, You can't do this in any cross-browser way. IE does have methods to enable "trusted" applications to use ActiveX objects to read/write file.
If you are trying to save it on your server then simply pass on the text data to your server and execute the file writing code using some server side language.
To store some information on the client side that is considerably small, you can go for cookies.
Using the HTML5 API for Local Storage.
If you are talking about browser javascript, you can not write data directly to local file for security reason. HTML 5 new API can only allow you to read files.
But if you want to write data, and enable user to download as a file to local. the following code works:
function download(strData, strFileName, strMimeType) {
var D = document,
A = arguments,
a = D.createElement("a"),
d = A[0],
n = A[1],
t = A[2] || "text/plain";
//build download link:
a.href = "data:" + strMimeType + "charset=utf-8," + escape(strData);
if (window.MSBlobBuilder) { // IE10
var bb = new MSBlobBuilder();
bb.append(strData);
return navigator.msSaveBlob(bb, strFileName);
} /* end if(window.MSBlobBuilder) */
if ('download' in a) { //FF20, CH19
a.setAttribute("download", n);
a.innerHTML = "downloading...";
D.body.appendChild(a);
setTimeout(function() {
var e = D.createEvent("MouseEvents");
e.initMouseEvent("click", true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
a.dispatchEvent(e);
D.body.removeChild(a);
}, 66);
return true;
}; /* end if('download' in a) */
//do iframe dataURL download: (older W3)
var f = D.createElement("iframe");
D.body.appendChild(f);
f.src = "data:" + (A[2] ? A[2] : "application/octet-stream") + (window.btoa ? ";base64" : "") + "," + (window.btoa ? window.btoa : escape)(strData);
setTimeout(function() {
D.body.removeChild(f);
}, 333);
return true;
}
to use it:
download('the content of the file', 'filename.txt', 'text/plain');
Try
let a = document.createElement('a');
a.href = "data:application/octet-stream,"+encodeURIComponent("My DATA");
a.download = 'abc.txt';
a.click();
If you want to download binary data look here
Update
2020.06.14 I upgrade Chrome to 83.0 and above SO snippet stop works (reason: sandbox security restrictions) - but JSFiddle version works - here
Above answer is useful but, I found code which helps you to download text file directly on button click.
In this code you can also change filename as you wish. It's pure javascript function with HTML5.
Works for me!
function saveTextAsFile()
{
var textToWrite = document.getElementById("inputTextToSave").value;
var textFileAsBlob = new Blob([textToWrite], {type:'text/plain'});
var fileNameToSaveAs = document.getElementById("inputFileNameToSaveAs").value;
var downloadLink = document.createElement("a");
downloadLink.download = fileNameToSaveAs;
downloadLink.innerHTML = "Download File";
if (window.webkitURL != null)
{
// Chrome allows the link to be clicked
// without actually adding it to the DOM.
downloadLink.href = window.webkitURL.createObjectURL(textFileAsBlob);
}
else
{
// Firefox requires the link to be added to the DOM
// before it can be clicked.
downloadLink.href = window.URL.createObjectURL(textFileAsBlob);
downloadLink.onclick = destroyClickedElement;
downloadLink.style.display = "none";
document.body.appendChild(downloadLink);
}
downloadLink.click();
}
const data = {name: 'Ronn', age: 27}; //sample json
const a = document.createElement('a');
const blob = new Blob([JSON.stringify(data)]);
a.href = URL.createObjectURL(blob);
a.download = 'sample-profile'; //filename to download
a.click();
Check Blob documentation here - Blob MDN to provide extra parameters for file type. By default it will make .txt file
In the case it is not possibile to use the new Blob solution, that is for sure the best solution in modern browser, it is still possible to use this simpler approach, that has a limit in the file size by the way:
function download() {
var fileContents=JSON.stringify(jsonObject, null, 2);
var fileName= "data.json";
var pp = document.createElement('a');
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
pp.setAttribute('download', fileName);
pp.click();
}
setTimeout(function() {download()}, 500);
$('#download').on("click", function() {
function download() {
var jsonObject = {
"name": "John",
"age": 31,
"city": "New York"
};
var fileContents = JSON.stringify(jsonObject, null, 2);
var fileName = "data.json";
var pp = document.createElement('a');
pp.setAttribute('href', 'data:text/plain;charset=utf-8,' + encodeURIComponent(fileContents));
pp.setAttribute('download', fileName);
pp.click();
}
setTimeout(function() {
download()
}, 500);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<button id="download">Download me</button>
Use the code by the user #useless-code above (https://stackoverflow.com/a/21016088/327386) to generate the file.
If you want to download the file automatically, pass the textFile that was just generated to this function:
var downloadFile = function downloadURL(url) {
var hiddenIFrameID = 'hiddenDownloader',
iframe = document.getElementById(hiddenIFrameID);
if (iframe === null) {
iframe = document.createElement('iframe');
iframe.id = hiddenIFrameID;
iframe.style.display = 'none';
document.body.appendChild(iframe);
}
iframe.src = url;
}
I found good answers here, but also found a simpler way.
The button to create the blob and the download link can be combined in one link, as the link element can have an onclick attribute. (The reverse seems not possible, adding a href to a button does not work.)
You can style the link as a button using bootstrap, which is still pure javascript, except for styling.
Combining the button and the download link also reduces code, as fewer of those ugly getElementById calls are needed.
This example needs only one button click to create the text-blob and download it:
<a id="a_btn_writetofile" download="info.txt" href="#" class="btn btn-primary"
onclick="exportFile('This is some dummy data.\nAnd some more dummy data.\n', 'a_btn_writetofile')"
>
Write To File
</a>
<script>
// URL pointing to the Blob with the file contents
var objUrl = null;
// create the blob with file content, and attach the URL to the downloadlink;
// NB: link must have the download attribute
// this method can go to your library
function exportFile(fileContent, downloadLinkId) {
// revoke the old object URL to avoid memory leaks.
if (objUrl !== null) {
window.URL.revokeObjectURL(objUrl);
}
// create the object that contains the file data and that can be referred to with a URL
var data = new Blob([fileContent], { type: 'text/plain' });
objUrl = window.URL.createObjectURL(data);
// attach the object to the download link (styled as button)
var downloadLinkButton = document.getElementById(downloadLinkId);
downloadLinkButton.href = objUrl;
};
</script>
Here is a single-page local-file version for use when you need the extra processing functionality of a scripting language.
Save the code below to a text file
Change the file extension from '.txt' to '.html'
Right-click > Open With... > notepad
Program word processing as needed, then save
Double-click html file to open in default browser
Result will be previewed in the black box, click download to get the resulting text file
Code:
<!DOCTYPE HTML>
<HTML>
<HEAD>
</HEAD>
<BODY>
<SCRIPT>
// do text manipulation here
let string1 = 'test\r\n';
let string2 = 'export.';
// assemble final string
const finalText = string1 + string2;
// convert to blob
const data = new Blob([finalText], {type: 'text/plain'});
// create file link
const link = document.createElement('a');
link.innerHTML = 'download';
link.setAttribute('download', 'data.txt');
link.href = window.URL.createObjectURL(data);
document.body.appendChild(link);
// preview the output in a paragraph
const htmlBreak = string => {
return string.replace(/(?:\r\n|\r|\n)/g, '<br>');
}
const preview = document.createElement('p');
preview.innerHTML = htmlBreak(finalText);
preview.style.border = "1px solid black";
document.body.appendChild(preview);
</SCRIPT>
</BODY>
</HTML>

Creating a file and triggering download in Javascript

I've got a really simple line in my code that should trigger the download of a file created on the go.
window.open(window.URL.createObjectURL(new Blob(["Example of something being written into a file then downloaded"], {type: "text/plain"})));
But for some reason, this does not work. A new window starts appearing, and then suddenly disappears.
Any clue why this doesn't work?
EDIT: If I call
`window.location = window.URL.createObjectURL(new Blob(["Example of something being written into a file then downloaded"], {type: "text/plain"}));`
It opens the file. But nothing was downloaded.
Try this solution
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
return function () {
var data = "Your data...........",
fileName = "filename";
blob = new Blob(data, {type: "text/plain"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.text = "download file";
window.URL.revokeObjectURL(url);
};
}());
this will create new <a> element. You can download the file by clicking it.
This needs HTML 5 support and for more options, check answers for this question.

Javascript display filename instead of blob name in the PDF URL

I am able to get the pdf in the new window with URL as
htts://mydomainname/410-8d9c-4883-86c5-d76c50a24a1d
I want to remove the auto generated blob name (410-8d9c-4883-86c5-d76c50a24a1d) in the generated URL and place my custom name link below
htts://mydomainname/filename
What modifications i need to do for below code
var file = new Blob([response], {type: 'application/pdf'});
var fileURL = URL.createObjectURL(file);
$window.open(fileURL);
Not sure exactly where this code lives for you, but here is a solution using XmlHttpRequest "onload".
oReq.onload = function(e) {
if (this.status === 200) {
const blob = new Blob([oReq.response], { type: "image/pdf"})
let a = document.createElement("a");
a.style = "display: none";
document.body.appendChild(a);
let url = window.URL.createObjectURL(blob);
a.href = url;
a.download = 'myFile.pdf'; // gives it a name via an a tag
a.click();
window.URL.revokeObjectURL(url);
} else {
// handler error eee
}
}
Basically rather than $window.open(fileURL); you need to programmatically create a anchor tag, setting its href with the window.URL.createObjectURL as youve done above.
Hope this helps,
Matt

Creating Javascript Blob() with data from HTML Element. Then downloading it as a text file

I'm using an HTML5 site to create a log per-say within a textarea element. I need to pull the data from that area with the click of a button, and download it to my computer via a .txt file. How would I go about doing this if it is possible??
HTML:
<input type="button" onclick="newBlob()" value="Clear and Export">
Javascript:
function newBlob() {
var blobData = document.getElementById("ticketlog").value;
var myBlob = new Blob(blobData, "plain/text");
blobURL = URL.createObjectURL(myBlob);
var href = document.createElement("a");
href.href = blobURL;
href.download = myBlob;
href.id = "download"
document.getElementById("download").click();
}
I figure if I make the Blob, create a URL for it, map the URL to an "a" element then auto-click it then it should work in theory. Obviously I'm missing something though. Any help would be fantastic. 1st question on this site btw:p
The simplest way I've come up with is as follows:
function download(text, filename){
var blob = new Blob([text], {type: "text/plain"});
var url = window.URL.createObjectURL(blob);
var a = document.createElement("a");
a.href = url;
a.download = filename;
a.click();
}
download("this is the file", "text.txt");
List of possible blob filestypes: http://www.freeformatter.com/mime-types-list.html
const downloadBlobAsFile = (function closure_shell() {
const a = document.createElement("a");
return function downloadBlobAsFile(blob, filename) {
const object_URL = URL.createObjectURL(blob);
a.href = object_URL;
a.download = filename;
a.click();
URL.revokeObjectURL(object_URL);
};
})();
document.getElementById("theButton").addEventListener("click", _ => {
downloadBlobAsFile(new Blob(
[document.getElementById("ticketlog").value],
{type: "text/plain"}
), "result.txt");
});
The value of a download property of an <a> element is the name of the file to download, and the constructor of Blob is Blob(array, options).
I used this approach that doesn't involve creating an element and revokes the textFile after the browser showed the text file
var text = 'hello blob';
var blob = new Blob([text], { type: 'text/plain' });
let textFile = window.URL.createObjectURL(blob);
let window2 = window.open(textFile, 'log.' + new Date() + '.txt');
window2.onload = e => window.URL.revokeObjectURL(textFile);

Chrome extension/jQuery works on one site but not others? Trying to fire an event on clicking a link

I have three different js files for three different sites. Let me preface by saying the manifest does have the proper settings to have these these on the proper sites, and only one function of the extension (the most important one) does not work.
The first, which works, is for pages like these: http://hearthstonetopdeck.com/deck.php?d=1613
var decklist = [];
$('.cardname').each(function(i, el) {
var values = $(this).text().split(' ');
var count = parseInt(values.shift(), 10);
for (var i = 0; i < count; i++) {
decklist.push(values.join(' '));
}
});
var data = decklist.join("\r\n");
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var blob = new Blob([data], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
$(document).ready(function(){
var html = $('#deckname').html() + '';
fileName = $('#deckname').text() + '.txt';
html = html.replace(/<h1>#/, '<h1><a class="download" href="#download">DOWNLOAD</a> - #');
$('#deckname').html(html);
});
$(document).ready(function(){
$('a[href="#download"]').click(function(){
saveData(data, fileName);
});
});
Running this in the console will work just as it does with the extension. I have tested all 3 of these js files both using the chrome extension method and pasting in the console. Results are identical.
The second site (http://www.hearthhead.com/deck=300/spell-power-on-a-budget), for which it USED to work, no longer does. I can't seem to remember change any code either, and it should fire identically. The issue here is that, while the download link appears, either the event doesn't fire or it simply doesn't work. Here is the code for site #2:
var decklist = [];
$('.deckguide-cards-type li').each(function(i, el) {
var values = $(this).text().substring(1).split(' ');
if ($.inArray("x2", values) != "-1") {
values.pop();
decklist.push(values.join(' '));
}
decklist.push(values.join(' '));
});
var data = decklist.join("\r\n");
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var blob = new Blob([data], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
$(document).ready(function(){
$('a[href="#download"]').click(function(){
saveData(data, fileName);
});
});
$(document).ready(function(){
var html = $('.text h1').html() + ' hearthstonedeckdl';
fileName = $('.text h1').text() + '.txt';
html = html.replace(/hearthstonedeckdl/, '- <a class="download" href="#download">DOWNLOAD</a>');
$('.text h1').html(html);
});
Firing the function saveData on load DOES work exactly as expected, and a .txt file is downloaded with the proper data. This is the intended function on clicking the download link, and it works in the first example.
This final example has not worked period, but as before, firing on load works, properly. It's simply the link I'm having issues with. The site is here: http://www.hearthpwn.com/decks/46364-d3managements-legend-hunter
The code is below:
var decklist = [];
$('.col-name').each(function(i, el) {
var values = $(this).text().substring(2).substring(0, $(this).text().length - 10).replace(/[^a-zA-Z0-9\.\s']+/g ,"").split(' ');
if ($.inArray("", values) != "-1") {
return;
} else if ($(this).text().substr($(this).text().length - 3, 1) == "2") {
decklist.push(values.join(' '));
decklist.push(values.join(' '));
} else {
decklist.push(values.join(' '));
}
});
var data = decklist.join("\r\n");
var saveData = (function () {
var a = document.createElement("a");
document.body.appendChild(a);
a.style = "display: none";
return function (data, fileName) {
var blob = new Blob([data], {type: "octet/stream"}),
url = window.URL.createObjectURL(blob);
a.href = url;
a.download = fileName;
a.click();
window.URL.revokeObjectURL(url);
};
}());
$(document).ready(function(){
$('a[href="#download"]').click(function(){
saveData(data, fileName);
});
});
$(document).ready(function(){
var html = $('.t-deck-title').html() + ' hearthstonedeckdl';
fileName = $('.t-deck-title').text() + '.txt';
html = html.replace(/hearthstonedeckdl/, '</br><a class="download" href="#download">DOWNLOAD</a>');
$('.t-deck-title').html(html);
});
I'm fairly new to jQuery, but consulting with a friend of mine that has more experience than me can't seem to find the issue, and it's driving me absolutely mad.
Thanks!
You declare a click event on an anchor before it is created.
Replace this:
$(document).ready(function(){
$('a[href="#download"]').click(function(){
saveData(data, fileName);
});
});
With this:
$(document).ready(function(){
$(document).on('click', 'a[href="#download"]', function(){
saveData(data, fileName);
});
});
Or keep your code and make sure you call this:
var html = $('.t-deck-title').html() + ' hearthstonedeckdl';
fileName = $('.t-deck-title').text() + '.txt';
html = html.replace(/hearthstonedeckdl/, '</br><a class="download" href="#download">DOWNLOAD</a>');
$('.t-deck-title').html(html);
before attaching the click event.
Have you tried giving jquery another namespace? I noticed on the site you provided does not run jquery which might mean on the other sites it may be conflicting.
try
var $jg = jQuery.noConflict();
at the top of your document.
Then instead of
$('.t-deck-title')
try
$jg('.t-deck-title')

Categories