Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preserving newline characters in data:text URI

I have a button in my extension that triggers the following code:

chrome.tabs.create({url: 'data:text;base64,'+btoa(data), active:false});

This triggers a download of my string (data), as I expected. Unfortunately, it seems to be stripping out newline characters.

I have tried other encoding methods, including utf-8 and the encodeUri() function. I also tried switching the mimetype to data:text/plain, but that simply opens in a new tab (with the correct newline characters) instead of downloading.

Is there a way to encode my text so that newline characters are preserved? If not, is there a different method for triggering file downloads in the browser?

edit

I have discovered that the newlines do appear in some text editors. Previously, I was using notepad, which did not recognize the newline characters from chrome, but my other text editor (notepad++) does seem to recognize them

like image 530
MrGlass Avatar asked Mar 24 '23 06:03

MrGlass


1 Answers

My recommended solution is to not use Notepad, because it does not recognize non-Windows line formats. If you still want to be able to use Notepad with your output, replace all line feeds (0x0A) with carriage return+line feed pairs (0x0D 0x0A).

chrome.tabs.create({
    url: 'data:text;base64,' + btoa(data.replace(/\n/g, '\r\n')),
    active: false
});
like image 180
Rob W Avatar answered Apr 27 '23 10:04

Rob W