0
votes

I have some questions regarding google calendar script that I'm building. So I managed to write the script and deploy it as a web app, but I encountered some problems:

1) It should list all current day events, but it lists only one event of the day 2) Also I want to display only the title of the event (it’s working now) and the start time and end time of the event. I managed to display a title (events[i].summary) and the start time of the event, but I was unable to display end time of the event and to change the format of the time that it would display time like this for example : 1pm – 2 pm. 3) Also what I want to do is to make the script run without pressing a button. I want it to work every time I open the published web app or refresh the web app page.

Here is the script code:

function doGet() {
return HtmlService.createHtmlOutputFromFile('calendarApp');
}


function listEvents() {
var actualDate = new Date();
var endOfDayDate = new      
Date(actualDate.getFullYear(),actualDate.getMonth(),actualDate.getDate(),23,59,59);                                                   
var calendarId = 'primary';
var optionalArgs = {
timeMin: (new Date()).toISOString(),
timeMax: endOfDayDate.toISOString(),
showDeleted: false,
singleEvents: true,
maxResults: 10,
orderBy: 'startTime'
};


var response = Calendar.Events.list(calendarId, optionalArgs);
var events = response.items;


var allEvents = [];
if (events && events.length > 0) {
for (i = 0; i < events.length; i++) {
allEvents.push(events[i].summary + ' ' + events[i].start.dateTime);
}
return allEvents;
} else {
return ['No events found'];
}

And this is a HTML code:

<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<h1>Calendar App</h1>

<button onclick="listEvents()">List events</button>

<ul id='events'></ul>

<script>
function listEvents() {
 google.script.run
 .withSuccessHandler(function(response){
 var events = response;
 for(var i = 0; i < events.length; i++) {
 document.getElementById('events').innerHTML = '<li>' + response[i] + '</li>';
 }
 })
 .withFailureHandler(function(err){
 console.log(err);
 })
 .listEvents();
};
</script>
</body>
</html>

This is the link to actual google scritp: Google Script

Thank you in advance for your help :)

2

2 Answers

0
votes

Here is your modified (and working) code. You don't need to use advanced Calendar API since everything you need is available in CalendarApp, including a convenient getEventsForDay(). It shows all your events on opening as required.

code :

function doGet() {
  return HtmlService.createHtmlOutputFromFile('calendarApp').setTitle('CalendarApp');
}

function listEvents() {
  var today = new Date();
  var cal = CalendarApp.getDefaultCalendar();
  var events = cal.getEventsForDay(today);
  var data = [];
  data.push("Events for today "+Utilities.formatDate(today,Session.getScriptTimeZone(),"MMM dd yyyy"));
  if (events && events.length > 0) {
    for (i = 0; i < events.length; i++) {
      data.push(events[i].getTitle()+' : '+Utilities.formatDate(events[i].getStartTime(),Session.getScriptTimeZone(),"HH:mm")+' - '+Utilities.formatDate(events[i].getEndTime(),Session.getScriptTimeZone(),"HH:mm"))
    }
    return data;
  } else {
    return ['No events found','',''];
  }
}

html & script :

<!DOCTYPE html>
<html>
  <head>
    <base target="_top">
  </head>
  <body style="font-family:arial,sans;font-size:12pt">
    <h2>Calendar App</h2>
    <div id="events">
    </div>
    <script>
    function listEvents() {
     google.script.run
     .withSuccessHandler(function(events){
     document.getElementById('events').innerHTML = document.getElementById('events').innerHTML+'<p>' + events[0] + '</p>';
     for(var i = 1; i < events.length; i++) {
     document.getElementById('events').innerHTML = document.getElementById('events').innerHTML+'<li>' + events[i] + '</li>';
     }
     })
     .withFailureHandler(function(err){
     console.log(err);
     })
     .listEvents();
    };
    window.onload = listEvents();
    </script>
  </body>
</html>
0
votes

Here's a function I use to get my calendar events for the next 5 weeks. And I use it in conjunction with a webapp so it gets returned to a statement that looks like this document.getElementById('hotbox').innerHTML=hl; hotbox is just a div.

function getMyEvents()
{
  var allCals=CalendarApp.getAllCalendars();
  var s=Utilities.formatString('<strong>%s</strong>',Utilities.formatDate(new Date(),Session.getScriptTimeZone(),"E MMM d, yyyy HHmm"))
  var min=60 * 1000;
  var hr=60 * min;
  var day=24 * hr;
  var wk=7 * day;
  var start = new Date(new Date().setHours(0,0,0));
  var end=new Date(start.valueOf() + (5 * wk));//you could make this + day instead of + (5 * wk)
  var incl=['Calendar1Name','Calendar2Name'];//These are different calendar names as I have some special calendars for different functions
  for(var i=0;i<allCals.length;i++)
  {
    if(incl.indexOf(allCals[i].getName())>-1)
    {
      s+=Utilities.formatString('<br /><strong>%s</strong>',allCals[i].getName());
      var events=allCals[i].getEvents(start, end);
      if(events)
      {
        s+='<br><ul>';
        for(j=0;j<events.length;j++)
        {
          var calId=allCals[i].getId();
          var evId=events[j].getId();
          if(events[j].isAllDayEvent())
          {
            s+=Utilities.formatString('<li><strong>%s</strong>-%s %s <input type="checkbox" class="markdone" title="Delete Event" name="delevent" value="%s,%s" /></li>', events[j].getTitle(),'All Day',Utilities.formatDate(events[j].getStartTime(),Session.getScriptTimeZone(),"E MMM d"),calId,evId);
          }
          else
          {
            s+=Utilities.formatString('<li><strong>%s</strong>-%s <input type="checkbox" class="markdone" title="Delete Event" name="delevent" value="%s,%s" /></li>', events[j].getTitle(),Utilities.formatDate(events[j].getStartTime(),Session.getScriptTimeZone(),"E MMM d, HHmm"),calId,evId);
          }
        }
        s+='</ul>';
      }
    }
  }
  s+='<br /><input type="button" value="Delete Selected Events" onClick="delSelectedEvents();" style="width:250px;height:35px;text-align:center;margin:10px 0 10px 0;" />';
  //var ui=HtmlService.createHtmlOutput(s);
  //SpreadsheetApp.getUi().showModelessDialog(ui, 'My Events');
  return s;
}