Link to .ics file on mobile

I would like to be able to have a user click a button, which generates an .ics file that is then opened by their default mail client, and added to calendar.

I dont see a nice native way to do this, so i've made a workaround - which works. Just want to know if there is perhaps a better way.

Steps:
Link a button that opens a standard[non-mobile] retool app, that app just has a single javascript query which is set to trigger on page load - the JS just generate the .ics file and triggers a download.

heres the javascript:

function createICSInvite() {
  // Create a new Date object for the start time (adjust as needed)
  var startDate = new Date('2022-03-16T10:00:00-04:00');
  
  // Create a new Date object for the end time (adjust as needed)
  var endDate = new Date('2022-03-16T11:00:00-04:00');
  
  // Format the start and end times as UTC time strings (in the format YYYYMMDDTHHMMSSZ)
  var start = startDate.getUTCFullYear() +
              ('0' + (startDate.getUTCMonth() + 1)).slice(-2) +
              ('0' + startDate.getUTCDate()).slice(-2) + 'T' +
              ('0' + startDate.getUTCHours()).slice(-2) +
              ('0' + startDate.getUTCMinutes()).slice(-2) +
              ('0' + startDate.getUTCSeconds()).slice(-2) + 'Z';
              
  var end = endDate.getUTCFullYear() +
            ('0' + (endDate.getUTCMonth() + 1)).slice(-2) +
            ('0' + endDate.getUTCDate()).slice(-2) + 'T' +
            ('0' + endDate.getUTCHours()).slice(-2) +
            ('0' + endDate.getUTCMinutes()).slice(-2) +
            ('0' + endDate.getUTCSeconds()).slice(-2) + 'Z';

  // Encode the event details in a data URI
  var dataURI = encodeURI('data:text/calendar;charset=utf-8,' + [
    'BEGIN:VCALENDAR',
    'VERSION:2.0',
    'PRODID:-//My Company//NONSGML Event//EN',
    'BEGIN:VEVENT',
    'UID:' + Math.random().toString(36).substr(2, 9),
    'DTSTAMP:' + start,
    'DTSTART:' + start,
    'DTEND:' + end,
    'SUMMARY:Example Event',
    'DESCRIPTION:This is an example event.',
    'LOCATION:123 Main St.',
    'END:VEVENT',
    'END:VCALENDAR'
  ].join('\n'));

  // Create a new anchor element with the data URI as the href attribute
  var link = document.createElement('a');
  link.setAttribute('href', dataURI);
  link.setAttribute('download', 'event.ics');
  
  // Programmatically click the link to open the user's email client with the event attached
  link.click();
}

I just replace the static text with urlparams, and voila.

Just want to see if there's a cleaner method.

Thanks!

2 Likes

Thanks for sharing this @msd5079 This approach looks good to me, but curious if anyone from our community has other ideas!