Reputation: 31
I am a novice to javascript trying to create a .txt file from an .htm document on my PC.
The following code works well with IE, and creates a file (say "A1.txt") on my desktop. However, I can not able to create the file using Chrome. I am running Windows Vista.
Let me know what modification I need to carry out to run this code using Chrome.
Thanks in advance
<html>
<head>
<script type="text/javascript" language="javascript">
</script></head>
<body>
<form name="F1">PN<input type="text" name="T1"></form>
<p><input type="button" value="Submit" onclick="dp()"></p>
</body></html>
<script>
myObject = new ActiveXObject("WScript.Shell");
function dp()
{T1 = "";
var txtfile = "A"+document.F1.T1.value+".txt";
var fso = new ActiveXObject("Scripting.FileSystemObject");
var myFile = fso.OpenTextFile(txtfile,8, true,0);
myFile.write("Test");
myFile.Close();
fso = null;
}
</script>
Please help.
Upvotes: 0
Views: 1885
Reputation: 1582
Use the HTML5 File API
function dp() {
if ('Blob' in window) {
var fileName = "A" + document.F1.T1.value;
var textToWrite = "Test";
var textFileAsBlob = new Blob([textToWrite], {
type: 'text/plain'
});
var downloadLink = document.createElement("a");
downloadLink.download = fileName;
downloadLink.innerHTML = "Download File";
if ('webkitURL' in window) {
// 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();
} else {
alert('Your browser does not support the HTML5 Blob.');
}
}
See more detailed sample here.
Upvotes: 1