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>
I am trying to run js script in the chrome-console of Linkedin page.
The script needs to take an array and download .csv file of the array.
When I run it on google.com or any other website, it works fine. But when I run it on Linkedin I got this error:
Refused to run the JavaScript URL because it violates the following Content Security Policy directive:
"script-src 'report-sample' 'sha256-6gLjSWp3GRKZCUFvRX5aGHtECD1wVRgJOJp7r0ZQjV0=' 'unsafe-inline' static.licdn.com s.c.lnkd.licdn.com static-fstl.licdn.com static-src.linkedin.com
https://www.linkedin.com/voyager/service-worker-push.js
https://platform.linkedin.com/js/analytics.js static-exp1.licdn.com static-exp2.licdn.com s.c.exp1.licdn.com s.c.exp2.licdn.com static-lcdn.licdn.com s.c.lcdn.licdn.com https://www.linkedin.com/sc/ https://www.linkedin.com/scds/ https://qprod.www.linkedin.com/sc/ https://www.linkedin.com/sw.js https://www.linkedin.com/voyager/abp-detection.js https://platform.linkedin.com/litms/utag/ https://platform.linkedin.com/litms/vendor/".
Note that 'unsafe-inline' is ignored if either a hash or nonce value is present in the source list.
That's the code I am trying to run:
rowsso = [["#: ", "Name: ", "Title: "], ["5","hi", "five"]];
let csvContentss = "data:text/csv;charset=utf-8,";
rowsso.forEach(function(rowArray){
let row = rowArray.join(",");
csvContentss += row + "\r\n";
});
var encodedUri = encodeURI(csvContentss);
var link = document.createElement("a");
link.setAttribute("href", encodedUri);
link.setAttribute("download", "my_data.csv");
document.body.appendChild(link); // Required for FF
link.click();
I tried to look for similar case, but couldn't find a way that fix it.
SOLVED the problem by using different method that doesn't violate CSP by using the following code:
This function receive a 2D Array and return String in appropriate format to later create the csv file:
function arrayToCSV (twoDiArray) {
var csvRows = [];
for (var i = 0; i < twoDiArray.length; ++i) {
for (var j = 0; j < twoDiArray[i].length; ++j) {
twoDiArray[i][j] = '\"' + twoDiArray[i][j] + '\"'; // Handle elements that contain commas
}
csvRows.push(twoDiArray[i].join(','));
}
var csvString = csvRows.join('\r\n');
return csvString;
}
With the return String, we send it to this function:
function downloadString(text, fileType, fileName) {
var blob = new Blob([text], { type: fileType });
var a = document.createElement('a');
a.download = fileName;
a.href = URL.createObjectURL(blob);
a.dataset.downloadurl = [fileType, a.download, a.href].join(',');
a.style.display = "none";
document.body.appendChild(a);
a.click();
document.body.removeChild(a);
setTimeout(function() { URL.revokeObjectURL(a.href); }, 1500);
}
So in the main in would look like this:
rowsso = [["#: ", "Name: ", "Title: "], ["5","hi", "five"]];
twoDArrStr = arrayToCSV(rowsso);
downloadString(twoDArrStr, "csv" , "csvFile.csv");
It works good, nevertheless, if someone can explain me better what is the reason this actually work and the other one doesn't I would be happy.
When you executing some script in console for specific website you execute it in the context of that website.
On linkedin website there may be some overrides for some standard methods, like override for appendChild and they have reimplemented such methods to do additional checking to make sure that someone will not execute unneded script from outside.
Also linkedin may have script that listen for DOM changes and if you want to place something strange into DOM they may prevent that.
UPDATE:
i see that there is problem with execution of
link.click()
on linkedin page, so they somehow prevent using click programmatically on link elements with csv format...
UPDATE:
I see that linkedin use: Content Security Policy
Please read more about it here: https://content-security-policy.com/
So they may not allow to generate csv on the fly in browser.
This question already has answers here:
mailto link with HTML body
(10 answers)
Closed 7 years ago.
I want to open (not send) an email with a content in HTML format.
I'm using mailto of javascript, and I have created a string that contains the html in c#.net, but the mail shows the tags instead of rendering HTML. I guess I am missing a content-type: text/html but how do I put it? or is there a more correct way to do open email with content ?
Here's the c#.net code that gets the html page
[HttpPost]
public ActionResult SetMailContent(int entreatyID)
{
Entreaties entreaty = db.Entreaties.Where(e => e.ID == entreatyID).FirstOrDefault();
if (entreaty == null)
{
return new HttpStatusCodeResult(HttpStatusCode.NotFound, "File Not Found");
}
StringWriter stringWriter = new StringWriter();
using (HtmlTextWriter writer = new HtmlTextWriter(stringWriter))
{
writer.RenderBeginTag(HtmlTextWriterTag.H1);
writer.Write(entreaty.OpenDate.ToString("dd/MM/yyyy"));
writer.RenderEndTag();
}
string msg = stringWriter.ToString();
return Json(new { message = msg});
}
and javascript code:
window.location = "mailto:mail#gmail.com?body=" + SetMailContent(EntreatyID) + "&subject= " + EntreatyID;
Thank you for your help.
You need to add the HTML content to the DOM, not just display it as a string. You can do this via jQuery for example:
$("#containerId").append($("your mail content"));
This question already has answers here:
How to load all the images from one of my folder into my web page, using Jquery/Javascript
(14 answers)
jQuery pull images from directory
(4 answers)
Closed 8 years ago.
I have got a task to display all images inside a folder using jquery.
For that i used the code
var imageFolder = '../../Images/Avatar/';
var imgsrc = imageFolder +'';
I need to get the images file name inside that folder avatar. How can I get the file name. There are lot of image files in that avatar folder also has some txt files.I only need jpg,png,gif images only.
try this way
HTML CODE:
<div id='fileNames'> </div>
JQUERY CODE:
var fileExt = {},
fileExt[0]=".png",
fileExt[1]=".jpg",
fileExt[2]=".gif";
$.ajax({
//This will retrieve the contents of the folder if the folder is configured as 'browsable'
url: '../../Images/Avatar/',
success: function (data) {
$("#fileNames").html('<ul>');
//List all png or jpg or gif file names in the page
$(data).find("a:contains(" + fileExt[0] + "),a:contains(" + fileExt[1] + "),a:contains(" + fileExt[2] + ")").each(function () {
var filename = this.href.replace(window.location.host, "").replace("http:///", "");
$("#fileNames").append( "<li>" + filename + "</li>");
});
$("#fileNames").append('</ul>');
}
});
Basic logic referred from this SO question Here
Happy Coding :)
I don't know that it will work or not but you can try this
Give the name of image 1,2,3,4.....
and than show image using for loop like.
var imageFolder = '../../Images/Avatar/';
var imgsrc="";
for(var i=1; i <= totalImage; i++){
imgsrc= imageFolder +i;
}
How can I preserve images in a response to an email activity?
The images in the email show when viewed in CRM - they are added as attachments. When I click the 'respond' button, write a response, and send the response the images are stripped from the email and are not attached to the email.
I have been trying all sorts of things with JScript .
I would rather not have to write anything other than JScript.
This is possible with javascript. I don't know what you tried but this can be done. I.e. catch the send event of your form and create the attachment with Javascript.
Other options are:
You could use a workflow to attach the note of the parent email to
the response. But then you will be forced to save your email wait a
little while (execution of the workflow) and then send the email.
Write plug-in code (but you won't use anything else but Javascript
Javascript to delete attachment:
function deleteAttachments(){
var notesId = {GUID of notes};
var objNotes = new Object();
objNotes.DocumentBody = null;
objNotes.FileName = null;
objNotes.FileSize = null;
objNotes.IsDocument = false;
updateRecord(notesId, objNotes, “AnnotationSet”);
}
function updateRecord(id, entityObject, odataSetName) {
var jsonEntity = window.JSON.stringify(entityObject);
var serverUrl = Xrm.Page.context.getServerUrl();
var ODATA_ENDPOINT = “/XRMServices/2011/OrganizationData.svc”;
var updateRecordReq = new XMLHttpRequest();
var ODataPath = serverUrl + ODATA_ENDPOINT;
updateRecordReq.open(‘POST’, ODataPath + “/” + odataSetName + “(guid’” + id + “‘)”, false);
updateRecordReq.setRequestHeader(“Accept”, “application/json”);
updateRecordReq.setRequestHeader(“Content-Type”, “application/json; charset=utf-8″);
updateRecordReq.setRequestHeader(“X-HTTP-Method”, “MERGE”);
updateRecordReq.send(jsonEntity);
}
I can access the attachments here: https:{org. URL}/xrmServices/2011/OrganizationData.svc/EmailSet(guid'3848cb4d-673f-e211-b9af-005056bd0001')/email_activity_mime_attachment
guid is the guid of the email.
The image is stored in d:Body as Base64.
Now all I need to do is rewrite img for each inline image with src="data:image/png;base64,theverylongstring...
All inline images will be preserved in the response as Base64.