Trigger click n a element created in javascript and download csv file - javascript

I'm trying to create an a element and trigger click event on it and down load a csv file on ajax response( the data array its for test purposes only)
$(document).on('click','.csv',function(){
var ticketid = $(this).attr('data-ticket');
$.ajax({
url: window.location.href,
method:'POST',
data: {
action:"export-csv",
ticketid: ticketid
},
}).done(function(response){
var data = [
['Foo', 'programmer'],
['Bar', 'bus driver'],
['Moo', 'Reindeer Hunter']
];
var response_object = $.parseJSON(response.html);
var result = toArray(response_object);
var csv = 'Name,Title\n';
data.forEach(function(row) {
csv += row.join(',');
csv += "\n";
});
console.log( encodeURI(csv));
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI(csv);
hiddenElement.target = '_blank';
hiddenElement.download = 'data.csv';
hiddenElement.click();
});
});
With this code there is no error but there is not download too.

Don't use trigger() on DOM object since it's a jQuery method, just .click() should do the work, Check the working example below :
hiddenElement.click();
Hope this helps.
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8, ABCD';
hiddenElement.download = 'aaa.csv';
hiddenElement.click();

Plain javascript doesn't have a trigger() method, only jQuery does.
To trigger a click you'd just do
hiddenElement.click();
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI('John,2018,House,312,3.75');
hiddenElement.download = 'aaa.csv';
hiddenElement.click();
This does require a browser that supports the download attribute

Triggering the click event of a link in via JS does not work - at least in Firefox (probably some kind of "security" restriction?). You'll have to create your own event and fire that:
var hiddenElement = document.createElement('a');
hiddenElement.href = 'data:text/csv;charset=utf-8,' + encodeURI('foo,bar,baz,42');
hiddenElement.download = 'aaa.csv';
hiddenElement.click();
var event = document.createEvent("MouseEvents");
event.initEvent("click", true, false);
hiddenElement.dispatchEvent(event, true);
Depending on which browsers you need to support, you might have to do a feature detection for older browsers (IE), checking for document.createEventObject, then using hiddenElement.fireEvent('onclick').

You Must Use SetAttribute Method :
<script>
var hiddenElement = document.createElement('a');
hiddenElement.setAttribute("href", "data:text/csv;charset=utf-8," + encodeURI(csv));
hiddenElement.setAttribute("download", 'aaa.csv');
hiddenElement.setAttribute("click", "DownloadFile(this)");
function DownloadFile(e) {
// Do Logic code here ..
}
</script>

Related

HTML Write to .txt 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>

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>

Error during JSON file download

I am trying to download JSON data into a JSON file using below mentioned code but the code just gives me a blank Internet Explorer. I need code to download JSON file without having any event raised at user interface.
var dataUri = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(JSONData));
var downloadAnchorNode = document.createElement('a');
downloadAnchorNode.setAttribute("href", dataUri);
downloadAnchorNode.setAttribute("download", "CarData.json");
downloadAnchorNode.click();
You are getting a blank page because you aren't inserting the anchor node into the DOM. Consider the following snippet. Even if you remove the download attribute, you will be taken to a page with JSON data on it.
var JSONData = {
foo: "bar"
};
var dataUri = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(JSONData));
var downloadAnchorNode = document.createElement('a');
downloadAnchorNode.innerHTML = "Click";
downloadAnchorNode.setAttribute("href", dataUri);
downloadAnchorNode.setAttribute("download", "CarData.json");
document.body.appendChild(downloadAnchorNode);
downloadAnchorNode.click();
Here it is without the download:
var JSONData = {
foo: "bar"
};
var dataUri = "data:text/json;charset=utf-8," + encodeURIComponent(JSON.stringify(JSONData));
var downloadAnchorNode = document.createElement('a');
downloadAnchorNode.innerHTML = "Click";
downloadAnchorNode.setAttribute("href", dataUri);
document.body.appendChild(downloadAnchorNode);
downloadAnchorNode.click();
Additionally, as others have pointed out, IE does not support the download attribute.

Change HTML downloadlink into downloadbutton through 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.

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