Tom Bar-Gal
Tom Bar-Gal

Reputation: 339

403 Error When Fetching Calendar List with Google Calendar API in Chrome Extension

I am developing a Chrome extension that interacts with the Google Calendar API. I've successfully implemented a function that fetches current and upcoming events, but I'm encountering a 403 error when trying to fetch the list of calendars using a similar function.

Here's the working function for fetching events:

enter code herefunction fetchCurrentAndUpcomingEvents(token) {
const now = new Date();
const oneHourLater = new Date(now.getTime() + (60 * 60 * 1000)); // One hour from now
const timeMin = now.toISOString();
const timeMax = oneHourLater.toISOString();

const endpoint = `https://www.googleapis.com/calendar/v3/calendars/primary/events?timeMin=${encodeURIComponent(timeMin)}&timeMax=${encodeURIComponent(timeMax)}&singleEvents=true&orderBy=startTime`;

return new Promise((resolve, reject) => {
    fetch(endpoint, {
        headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
        }
    })
    .then(response => response.json())
    .then(data => {
        const events = data.items;
        const currentEvents = [];
        const upcomingEvents = [];

        if (data && data.items) {
            const events = data.items; 
            events.forEach(event => {
                const eventStart = new Date(event.start.dateTime || event.start.date);
                if (eventStart <= now) {
                    currentEvents.push(event);
                } else {
                    upcomingEvents.push(event);
                }
            });
        }

        resolve({ currentEvents, upcomingEvents });
    })
    .catch(error => {
        reject(error);
    });
});
}

And here's the function that's giving me a 403 error when fetching calendars:

function fetchCalendars(token) {
const endpoint = 'https://www.googleapis.com/calendar/v3/users/me/calendarList';
console.log("Endpoint:", endpoint, "Token:", token); // Log the endpoint and token
return new Promise((resolve, reject) => {
    console.log("Fetching calendars with token:", token, "Endpoint:", endpoint);
    fetch(endpoint, {
        headers: {
            'Authorization': `Bearer ${token}`,
            'Content-Type': 'application/json'
        }
    })
    .then(response => {
        console.log('Response Status:', response.status); // Log the response status
        if (!response.ok) {
            throw new Error('Failed to fetch calendar list');
        }
        return response.json(); // Parse the JSON body of the response
    })
    .then(data => {
        console.log('Fetched calendars:', data.items); // Log the fetched calendar data
        resolve(data.items); // Resolve the promise with the calendar data
    })
    .catch(error => {
        console.error('Error fetching calendar list:', error);
        if (error.response) {
            console.error('Error response:', error.response);
        }
        reject(error);
    });
});
}

Both functions use the same OAuth token, which I've verified has the appropriate scopes for calendar access. The fetchCurrentAndUpcomingEvents function works perfectly, indicating that the token and request setup are correct. However, the fetchCalendars function fails with a 403 error.

I've confirmed that the Google Calendar API is enabled in my Google Cloud Console, the scopes are correctly set to include calendar access, and my OAuth consent screen is configured properly.

Here's the error I'm seeing in my console:

Fetching calendars with token: [TOKEN] Endpoint: https://www.googleapis.com/calendar/v3/users/me/calendarList
Response Status: 403 
Error fetching calendar list: Error: Failed to fetch calendar list

I'm not sure why I'm able to fetch events but not the calendar list with the same token. Any insights or suggestions would be greatly appreciated.

Upvotes: 0

Views: 74

Answers (1)

Tom Bar-Gal
Tom Bar-Gal

Reputation: 339

I found the answer

Instead of setting up the scopes in the backgound.js file as it should have been I've set it up in the Manifest. Once that was fixed I've successfully fetched the calendar list

Upvotes: 0

Related Questions