Reputation: 77
From what I've learned, there are two ways to work with the Google API in Chrome extensions: setting up OAuth and via Google Identity API. I've chosen to work with the ladder.
So I have no problems viewing calendars and events, but now I want to create events. I've been reading calendars using the following:
chrome.identity.getAuthToken({ interactive: true }, async function (token) {
//initialization (think they're all the same)
let init = {
method: "GET",
async: true,
headers: {
Authorization: "Bearer " + token,
"Content-Type": "application/json",
},
contentType: "json",
};
async function getCalendarId() {
return new Promise((resolve, reject) => {
fetch(
"https://www.googleapis.com/calendar/v3/calendars/primary",
init
)
.then((response) => response.json()) // Transform the data into json
.then(function (data) {
console.log(data["id"]);
var id = data["id"];
resolve(id);
});
});
}
calendarId = await getCalendarId();
await fetch(
"https://www.googleapis.com/calendar/v3/calendars/" +
calendarId +
"/events",
init
)
.then((response) => response.json()) // Transform the data into json
.then(async function (data) {
//get today to next week's events
for (var i = 0; i < data["items"].length; i++) {
//console.log(data["items"][i]);
if (data["items"][i]["end"] == undefined) {
console.log("found undefined");
} else {
//found a valid event
}
}
});
});
Upvotes: 1
Views: 692
Reputation: 201398
From i'll be using that access token of token to create an event. i think my authorization process is ok,
, I understood that you wanted a sample script for creating an event in Google Calendar using Javascript. In this case, how about the following sample script?
Please use your calendarId
and token
. eventObj
is a sample value. Please modify this for your actual situation.
// This object is a sample value. Please modify this for your actual situation.
const eventObj = {
"end": {
"dateTime": "2022-11-16T10:00:00-07:00",
"timeZone": "America/Los_Angeles"
},
"start": {
"dateTime": "2022-11-16T09:00:00-07:00",
"timeZone": "America/Los_Angeles"
},
"summary": "sample event title",
"description": "sample event description"
};
const options = {
method: "POST",
async: true,
headers: {
Authorization: "Bearer " + token,
"Content-Type": "application/json",
},
body: JSON.stringify(eventObj)
};
await fetch(
"https://www.googleapis.com/calendar/v3/calendars/" +
calendarId +
"/events",
options
)
.then((response) => response.json()) // Transform the data into json
.then((data) => console.log(data))
.catch((err) => console.log(err));
Upvotes: 1