Search code examples
javascriptbookmarklet

How to enter newline character in bookmarklet JavaScript


I try to write a bookmarklet which creates email, but there is an issue about using newline character.

When I execute the below code from Chrome Console, it works fine. However, this code doesn't work when executing from bookmarklet. I checked the code and the cause seems var body1 includes newline character(%0D%0A).

Anybody knows how to insert newline character in bookmarklet JS?

javascript:(function(){
var today = new Date();
var url = 'https://mail.google.com/mail/?view=cm';
var to = 'emailfrombookmarklet@example.com';
var subject = '【weather%20report】【' + today.getFullYear() + '-' + ("00" + (today.getMonth() + 1)).slice(-2) + '-' + ("00" + today.getDate()).slice(-2) + '%20bar】%20email%20from%20bookmarklet';
var body1 = 'Hi%2C%0D%0A%0D%0AThis is Kim Kardashian%2E%0D%0AIt%27s%20sunny%20today%2E%0D%0A%0D%0Adate%3A';
var targetDate = '%20' + today.getFullYear() + '-' + ("00" + (today.getMonth() + 1)).slice(-2) + '-' + ("00" + today.getDate()).slice(-2);
var body2 = '%0D%0AName%3A%20Kim%20Kardashian%0D%0A';
var body3 = '%0D%0ABest%20Regards%2C';
url += '&to=' + to + '&su=' + subject + '&body=' + body1 + targetDate + body2 + body3;
window.open(url);})();

Solution

  • It would be better to get rid of using encoded characters at all:

    javascript:(function() {
        var today = new Date();
        var url = 'https://mail.google.com/mail/?view=cm';
        var to = 'emailfrombookmarklet@example.com';
        var subject = '【weather report】【' + today.getFullYear() + '-' + ('00' + (today.getMonth() + 1)).slice(-2) + '-' + ('00' + today.getDate()).slice(-2) + ' bar】 email from bookmarklet';
        var body1 = 'Hi,\n\nThis is Kim Kardashian.\nIt\'s sunny today.\n\ndate:';
        var targetDate = ' ' + today.getFullYear() + '-' + ('00' + (today.getMonth() + 1)).slice(-2) + '-' + ('00' + today.getDate()).slice(-2);
        var body2 = '\nName: Kim Kardashian\n';
        var body3 = '\nBest Regards,';
        url += '&to=' + encodeURIComponent(to) + '&su=' + encodeURIComponent(subject) + '&body=' + encodeURIComponent(body1 + targetDate + body2 + body3);
        window.open(url);
    })();