How come the Google Calendar API in my Chrome extension doesn't update to display new events when I refresh the page after adding them through gcal?

the query

I'm facing an issue with displaying upcoming Google Calendar events on my Chrome extension using JavaScript and the Google Calendar API. The problem arises when I add new events on the Google Calendar website itself, as these events do not get refreshed or fetched by the extension. Even after signing out and re-authenticating, the new events are still not showing up, even though the old events display correctly.

An interesting observation is that this issue seems to be specific to certain calendars. Creating a new calendar seems to trigger a refresh of the events successfully.

approaches taken

As a novice in working with Google APIs, any guidance or suggestions would be greatly appreciated!

The current approach involves a function to fetch events from Google Calendar upon initial sign-in, which I assumed would also act as a refresh mechanism when retrieving data. However, for some calendars, this method fails to fetch new events. Suspecting a caching problem, I attempted to remove cache or include the 'Cache-Control': 'no-cache' tag in the headers while fetching calendar data, but this did not resolve the issue.

snippet

This is the function used to fetch events:

chrome.identity.getAuthToken({interactive: true}, function(token) {
    if (chrome.runtime.lastError) {
      return;
    }
  
    console.log("Authentication successful. Token:", token);
    isSignedIn = true;
    localStorage.setItem('gcal-signed-in',"true");
  
    var init = {
      method: 'GET',
      async: true,
      headers: {
        Authorization: 'Bearer ' + token,
        'Content-Type': 'application/json',
        'Cache-Control': 'no-cache'
      },
      'contentType': 'json'
    };

    const now = new Date();
    const isoNow = now.toISOString();
    const maxResults = 4;
  
    // retrieving all calendars
    fetch(`https://www.googleapis.com/calendar/v3/users/me/calendarList`, init)
    .then(response => response.json())
    .then(calendarListData => {
      calendarIds = calendarListData.items.map(calendar => calendar.id);

      const fetchPromises = [];
      let events = new Map();
      // fetching most recent events from each calendar
      for (const calendarId of calendarIds) {
        const fetchPromise = fetch(`https://www.googleapis.com/calendar/v3/calendars/${calendarId}/events?maxResults=${maxResults}&timeMin=${isoNow}`, init)
        .then((response) => response.json())
        .then((data) => {
          if (data.items) {
            data.items.forEach((event) => {
              const dateTimeParts = event.start.dateTime.split('T');
              const date = dateTimeParts[0];
              const time = dateTimeParts[1].substring(0, 5);
              const location = event.location; 
              console.log(location)
              
              // trim gets rid of leading and trailing white space/commas
              events.set([date, time], [event.summary.trim(),location]);
            });
          } else {
            console.log("No upcoming events found.");
          }
        })
        .catch((error) => {
          console.error("Error fetching events:", error);
        });
        fetchPromises.push(fetchPromise);
      }
// additional code for displaying the data using Promise.all(fetchPromises)

Your assistance is highly valued! Thank you.

Answer №1

Consider removing the maxResults parameter from the URL.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Efficiently Organizing Data Using Coldfusion Loops in Columns and Rows

My issue lies in pulling data from a database to display on my website. I have three keys/attributes (columns) - PostedDate, DataImage, and Source that need to be shown together in one div with the posted date at the top, image in the middle, and source at ...

Display your StencilJs component in a separate browser window

Looking for a solution to render a chat widget created with stenciljs in a new window using window.open. When the widget icon is clicked, a new window should open displaying the current state while navigating on the website, retaining the styles and functi ...

A guide on extracting data from an HTML table containing various input fields

I have a webpage with this table generated by a PHP script. What I need to do is extract the values from each of the 4 input fields and save them in separate JavaScript variables. Each button already has an onclick="fetchGrades(); trigger added. How can ...

javascript identifying a variable within location.href

Within my JavaScript code, there is a variable that holds a value: var selectedItemId = null; // the value is assigned by another function Next, there is a function defined like this: function editLink() { location.href = /*[[@{/supplycontracts/edit ...

Seamlessly adaptive HTML5 video playback

Has anyone figured out how to make an HTML5 video in an absolutely positioned <video> element resize to fit the window width and height without ever getting cropped? Many solutions I've come across rely on using the <iframe> tag, which is ...

Generating replicated elements at varying positions

After discovering that my previous question, which can be found here, is currently not feasible due to limitations with html2canvas only taking 'snapshots', I have chosen to approach the problem differently. The new approach involves making an o ...

Unable to retrieve PHP data using AJAX

Index.html → <form> <div class="form-group"> <!-- <input type="text" id="name" class="form-control" placeholder="Enter Name"> --> </div> <div ...

Sorting alphabetically, either by JAVA, JavaScript, or Idoc script

Currently, I have a task at hand that requires sorting items within categories alphabetically, with the exception of Examples. Special characters and numbers should be prioritized over letters in the sorting order. I've encountered an issue where mos ...

Generate selection choices by looping through a JSON document

I am attempting to develop a search box that will provide autocomplete suggestions based on user input from a key-value pair in a json file. I initially thought using datalist would be the most suitable approach for this task, however, upon running the cod ...

Improving animation performance on mobile devices using AngularJS

I've reached the final stages of developing a mobile application using AngularJS wrapped in a cordova webview. However, I'm encountering some issues with the panel transition animations. After experiencing strange behavior with ngAnimate, I deci ...

What is the proper way to implement the scrollToIndex feature in a FlatList component in React Native

I have a problem where I need to automatically scroll down by a specific value whenever a onPress event is triggered (in this case, the value is 499). However, the code I have tried does not seem to be working as expected. Here is the code snippet I am u ...

Validate form for radio group

Hello Experts, I am currently working on developing a form that includes a JavaScript validation function for a radio group. The main objective is to have a division pop up when either "Monday" or "Tuesday" is checked, and no popup when "None" is selected ...

Vue alerts and pop-ups will only show once

Utilizing vue ui to create a new project with Babel and Lint, I integrated dependencies vuetify, vuetify-loader, and vue-bootstrap. My goal was to have a simple 'open dialog' button that would reveal a dialog defined in a separate component file. ...

Capture the response from an AJAX request and store it in a JavaScript variable

I've been struggling to find a solution for this issue for quite some time now without any success. Here's what I'm trying to accomplish: I need to retrieve an array from my PHP file so that I can utilize it in my JavaScript code. Example. ...

Monitoring Clicks within an Iframe

Is there a way to track a click event on a hyperlink within an iframe using Google Analytics? The iframe is located within the same domain as the main page. How can this be achieved? The iframe is added dynamically to the page after it has loaded. Is i ...

Angular reactive forms can be customized to include a patched version of the matTime

I have an angular mattimepicker in my project. When trying to use it in a reactive form, I am encountering issues with patching the value to the edit form <h1>Reactive Form</h1> <form [formGroup]="form"> <mat-form-fie ...

The development of the React app will pause momentarily upon encountering a single low-severity vulnerability. To address this, you can either run `npm audit fix` to resolve it, or use `npm audit` to gain

A challenge arises while executing the command below in Visual Studio Code to develop a react app: create-react-app my-first-react-app The process halts and displays this message: found 1 low severity vulnerability run `npm audit fix` to rectify th ...

Exploring ThreeJS by Casting Rays on HTML Elements

We are currently encountering an issue with ThreeJS. Our goal is to integrate HTML elements into ThreeJS and use raycasting to determine whether we are pointing to any HTML element. However, when we intersect with it, it returns an empty array. An example ...

Leveraging server-sent events (SSE) for real-time updates on a web client using JavaScript

I have been experimenting with server-side events (SSE) in JavaScript and Node.JS to send updates to a web client. To simplify things, I created a function that generates the current time every second: setTimeout(function time() { sendEvent('time&a ...

Set datatables to perform regex searches that specifically target the beginning of text

Here is my JavaScript code for using datatables, I want to have the search function only filter results that start with the specified keyword. For example, if I have [hello, hello_all, all_hello] and my search term is "hel", I should only get [hello, hel ...