google classroom api to create a course using js - javascript

i am new with google classroom api and i want to create a course on local machine. can i do it or not ?
if create then how using javascript ?
as i try ,got an error with code =>403, status="PERMISSION_DENIED" and message=> "Request had insufficient authentication scopes."
in my code i use function createCourse() to create a new course.
my code is below given
<!DOCTYPE html>
<html>
<body>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize-button" style="display: none;">Authorize</button>
<button id="signout-button" style="display: none;">Sign Out</button>
<pre id="content"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = '782126680600-9kkg23inbnn9sv8ficcvjci2rgrnd648.apps.googleusercontent.com';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/classroom/v1/rest"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/classroom.courses.readonly";
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
createCourse();
listCourses();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* #param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Print the names of the first 10 courses the user has access to. If
* no courses are found an appropriate message is printed.
*/
function listCourses() {
gapi.client.classroom.courses.list({
pageSize: 10
}).then(function(response) {
console.info(response.result);
var courses = response.result.courses;
appendPre('Courses:');
if (courses.length > 0) {
for (i = 0; i < courses.length; i++) {
var course = courses[i];
appendPre(course.name)
}
} else {
appendPre('No courses found.');
}
});
}
function createCourse(){
var newCourse = {'name': '9th Math','ownerId' : 'me','courseState' : 'PROVISIONED'};
gapi.client.classroom.courses.create(newCourse).then(function(response) {
console.info(response);
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
please reply me..........

You have to update your scope from https://www.googleapis.com/auth/classroom.courses.readonly to https://www.googleapis.com/auth/classroom.courses.
According to the document, courses.create requires the following OAuth scope:https://www.googleapis.com/auth/classroom.courses to work.
The scope https://www.googleapis.com/auth/classroom.courses.readonly is used for listing and getting data. If there is a need to create, update you have to use https://www.googleapis.com/auth/classroom.courses to gain full access to the API.
Hope this helps.

Related

Using Google Sheet API through the new "Sign in with Google" instead of the old "Google Sign-in"

I am threatened by Google to quit using the old (but very effective) "Google Sign-in" because it will be deprecated on 31 Mar 2023. It is fine, but when I go for the new "Sign in with Google", I find that there are no documents explaining how this new authorization flow can integrate with Google Sheet API.
Ironically, even in Google Sheet API's documentations, the demos there are all still based on the old "Google Sign-in". Can anyone provide demo cases of how to read and insert values into Google Sheet based on the new "Sign in with Google"?
The Google sheets api quickstart for javascript has been updated to use web authorization.
You dont want to use signin unless you are working with Authencation, for google sheets you need authorization. The new library splits these two concepts.
<!DOCTYPE html>
<html>
<head>
<title>Sheets API Quickstart</title>
<meta charset="utf-8" />
</head>
<body>
<p>Sheets API Quickstart</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize_button" onclick="handleAuthClick()">Authorize</button>
<button id="signout_button" onclick="handleSignoutClick()">Sign Out</button>
<pre id="content" style="white-space: pre-wrap;"></pre>
<script type="text/javascript">
/* exported gapiLoaded */
/* exported gisLoaded */
/* exported handleAuthClick */
/* exported handleSignoutClick */
// TODO(developer): Set to client ID and API key from the Developer Console
const CLIENT_ID = '<YOUR_CLIENT_ID>';
const API_KEY = '<YOUR_API_KEY>';
// Discovery doc URL for APIs used by the quickstart
const DISCOVERY_DOC = 'https://sheets.googleapis.com/$discovery/rest?version=v4';
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
const SCOPES = 'https://www.googleapis.com/auth/spreadsheets.readonly';
let tokenClient;
let gapiInited = false;
let gisInited = false;
document.getElementById('authorize_button').style.visibility = 'hidden';
document.getElementById('signout_button').style.visibility = 'hidden';
/**
* Callback after api.js is loaded.
*/
function gapiLoaded() {
gapi.load('client', intializeGapiClient);
}
/**
* Callback after the API client is loaded. Loads the
* discovery doc to initialize the API.
*/
async function intializeGapiClient() {
await gapi.client.init({
apiKey: API_KEY,
discoveryDocs: [DISCOVERY_DOC],
});
gapiInited = true;
maybeEnableButtons();
}
/**
* Callback after Google Identity Services are loaded.
*/
function gisLoaded() {
tokenClient = google.accounts.oauth2.initTokenClient({
client_id: CLIENT_ID,
scope: SCOPES,
callback: '', // defined later
});
gisInited = true;
maybeEnableButtons();
}
/**
* Enables user interaction after all libraries are loaded.
*/
function maybeEnableButtons() {
if (gapiInited && gisInited) {
document.getElementById('authorize_button').style.visibility = 'visible';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick() {
tokenClient.callback = async (resp) => {
if (resp.error !== undefined) {
throw (resp);
}
document.getElementById('signout_button').style.visibility = 'visible';
document.getElementById('authorize_button').innerText = 'Refresh';
await listMajors();
};
if (gapi.client.getToken() === null) {
// Prompt the user to select a Google Account and ask for consent to share their data
// when establishing a new session.
tokenClient.requestAccessToken({prompt: 'consent'});
} else {
// Skip display of account chooser and consent dialog for an existing session.
tokenClient.requestAccessToken({prompt: ''});
}
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick() {
const token = gapi.client.getToken();
if (token !== null) {
google.accounts.oauth2.revoke(token.access_token);
gapi.client.setToken('');
document.getElementById('content').innerText = '';
document.getElementById('authorize_button').innerText = 'Authorize';
document.getElementById('signout_button').style.visibility = 'hidden';
}
}
/**
* Print the names and majors of students in a sample spreadsheet:
* https://docs.google.com/spreadsheets/d/1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms/edit
*/
async function listMajors() {
let response;
try {
// Fetch first 10 files
response = await gapi.client.sheets.spreadsheets.values.get({
spreadsheetId: '1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms',
range: 'Class Data!A2:E',
});
} catch (err) {
document.getElementById('content').innerText = err.message;
return;
}
const range = response.result;
if (!range || !range.values || range.values.length == 0) {
document.getElementById('content').innerText = 'No values found.';
return;
}
// Flatten to string to display
const output = range.values.reduce(
(str, row) => `${str}${row[0]}, ${row[4]}\n`,
'Name, Major:\n');
document.getElementById('content').innerText = output;
}
</script>
<script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
<script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>
</body>
</html>

How to implement Google Classroom API on VueJs project

I'm just getting started with Vue and the use of APIs. On my VueJs component, I want to use this code that I retrieved from here Google Classroom API Javascript. I want to retrieve the lists of classrooms that I handle when I clicked a button and display them on my view template.
The code below is retrieved from Google Classroom API:
<!DOCTYPE html>
<html>
<head>
<title>Classroom API Quickstart</title>
<meta charset="utf-8" />
</head>
<body>
<p>Classroom API Quickstart</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize_button" onclick="handleAuthClick()">Authorize</button>
<button id="signout_button" onclick="handleSignoutClick()">Sign Out</button>
<pre id="content" style="white-space: pre-wrap;"></pre>
<script type="text/javascript">
/* exported gapiLoaded */
/* exported gisLoaded */
/* exported handleAuthClick */
/* exported handleSignoutClick */
// TODO(developer): Set to client ID and API key from the Developer Console
const CLIENT_ID = '<YOUR_CLIENT_ID>';
const API_KEY = '<YOUR_API_KEY>';
// Discovery doc URL for APIs used by the quickstart
const DISCOVERY_DOC = 'https://classroom.googleapis.com/$discovery/rest';
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
const SCOPES = 'https://www.googleapis.com/auth/classroom.courses.readonly';
let tokenClient;
let gapiInited = false;
let gisInited = false;
document.getElementById('authorize_button').style.visibility = 'hidden';
document.getElementById('signout_button').style.visibility = 'hidden';
/**
* Callback after api.js is loaded.
*/
function gapiLoaded() {
gapi.load('client', intializeGapiClient);
}
/**
* Callback after the API client is loaded. Loads the
* discovery doc to initialize the API.
*/
async function intializeGapiClient() {
await gapi.client.init({
apiKey: API_KEY,
discoveryDocs: [DISCOVERY_DOC],
});
gapiInited = true;
maybeEnableButtons();
}
/**
* Callback after Google Identity Services are loaded.
*/
function gisLoaded() {
tokenClient = google.accounts.oauth2.initTokenClient({
client_id: CLIENT_ID,
scope: SCOPES,
callback: '', // defined later
});
gisInited = true;
maybeEnableButtons();
}
/**
* Enables user interaction after all libraries are loaded.
*/
function maybeEnableButtons() {
if (gapiInited && gisInited) {
document.getElementById('authorize_button').style.visibility = 'visible';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick() {
tokenClient.callback = async (resp) => {
if (resp.error !== undefined) {
throw (resp);
}
document.getElementById('signout_button').style.visibility = 'visible';
document.getElementById('authorize_button').innerText = 'Refresh';
await listCourses();
};
if (gapi.client.getToken() === null) {
// Prompt the user to select a Google Account and ask for consent to share their data
// when establishing a new session.
tokenClient.requestAccessToken({prompt: 'consent'});
} else {
// Skip display of account chooser and consent dialog for an existing session.
tokenClient.requestAccessToken({prompt: ''});
}
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick() {
const token = gapi.client.getToken();
if (token !== null) {
google.accounts.oauth2.revoke(token.access_token);
gapi.client.setToken('');
document.getElementById('content').innerText = '';
document.getElementById('authorize_button').innerText = 'Authorize';
document.getElementById('signout_button').style.visibility = 'hidden';
}
}
/**
* Print the names of the first 10 courses the user has access to. If
* no courses are found an appropriate message is printed.
*/
async function listCourses() {
let response;
try {
response = await gapi.client.classroom.courses.list({
pageSize: 10,
});
} catch (err) {
document.getElementById('content').innerText = err.message;
return;
}
const courses = response.result.courses;
if (!courses || courses.length == 0) {
document.getElementById('content').innerText = 'No courses found.';
return;
}
// Flatten to string to display
const output = courses.reduce(
(str, course) => `${str}${course.name}\n`,
'Courses:\n');
document.getElementById('content').innerText = output;
}
</script>
<script async defer src="https://apis.google.com/js/api.js" onload="gapiLoaded()"></script>
<script async defer src="https://accounts.google.com/gsi/client" onload="gisLoaded()"></script>
</body>
</html>
However, using this code results in numerous errors when attempted in my SynchButton.vue file inside methods. I also added the clientId and scope in my main.js file. I hope that you could all help me guys. Thank you all so much in advance!

Create google docs in google drive Javascript

I am creating an application using asp.net mvc and javascript in which I want to create a word document in my drive and view my created document in new tab,
I created a project in developer console and got my client Id and api key
I am unable to find any examples regarding this, below is my code of google docs api which is working fine,
<body>
<p>
Google Docs API Quickstart
</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize_button" style="display: none;">Authorize</button>
<button id="signout_button" style="display: none;">Sign Out</button>
<pre id="content"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = '<YOUR_CLIENT_ID>'
var API_KEY = '<YOUR_API_KEY>';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ['https://docs.googleapis.com/$discovery/rest?version=v1'];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/documents.readonly";
var authorizeButton = document.getElementById('authorize_button');
var signoutButton = document.getElementById('signout_button');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
printDocTitle();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* #param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Prints the title of a sample doc:
* https://docs.google.com/document/d/195j9eDD3ccgjQRttHhJPymLJUCOUjs-jmwTrekvdjFE/edit
*/
function printDocTitle() {
gapi.client.docs.documents.get({
documentId: '1Q0MGsSSqovVRiDadfnq9eCinoBnOuQn4hnh3-pOsbME'
}).then(function (response) {
var doc = response.result;
var title = doc.title;
appendPre('Document "' + title + '" successfully found.\n');
}, function (response) {
appendPre('Error: ' + response.result.error.message);
});
}
</script>
<script async="" defer="" onload="this.onload=function(){};handleClientLoad()" onreadystatechange="if (this.readyState === 'complete') this.onload()" src="https://apis.google.com/js/api.js"></script>
I believe your goal is as follows.
You want to create a new Google Document using Google Docs API with Javascript.
You have already been able to use Google Docs API.
In this case, how about the following modification?
Modified script:
First, please modify your scope from https://www.googleapis.com/auth/documents.readonly to https://www.googleapis.com/auth/documents.
And, please modify your script as follows.
From:
function printDocTitle() {
gapi.client.docs.documents.get({
documentId: '1Q0MGsSSqovVRiDadfnq9eCinoBnOuQn4hnh3-pOsbME'
}).then(function (response) {
var doc = response.result;
var title = doc.title;
appendPre('Document "' + title + '" successfully found.\n');
}, function (response) {
appendPre('Error: ' + response.result.error.message);
});
}
To:
function printDocTitle() {
gapi.client.docs.documents.create({
resource: {title: "sampleTitle"}
}).then(function (response) {
var doc = response.result;
var title = doc.title;
appendPre('Document "' + title + '" successfully found.\n');
}, function (response) {
appendPre('Error: ' + response.result.error.message);
});
}
When this script is run, a new Google Document with the title of "sampleTitle" is created to the root folder.
Reference:
Method: documents.create

How to get only certain events from a public google calendar and insert the event date in a js countdown

Here below the code from the [https://developers.google.com/calendar/quickstart/js][1], which is giving me on my browser the next
10 scheduled events for the Miami Dolphin taken from the google calendar,
<!DOCTYPE html>
<html>
<head>
<title>Google Calendar API Quickstart</title>
<meta charset="utf-8" />
</head>
<body>
<p>Google Calendar API Quickstart</p>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize_button" style="display: none;">Authorize</button>
<button id="signout_button" style="display: none;">Sign Out</button>
<pre id="content" style="white-space: pre-wrap;"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = '229529787511-d3t1rtegj0stfip9k65el11o6lv9km97.apps.googleusercontent.com';
var API_KEY = 'AIzaSyCy1chATNeTPNd3pUbzF84UAibd4In2JQw';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/calendar.readonly";
var authorizeButton = document.getElementById('authorize_button');
var signoutButton = document.getElementById('signout_button');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
}, function(error) {
appendPre(JSON.stringify(error, null, 2));
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listUpcomingEvents();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* #param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Print the summary and start datetime/date of the next ten events in
* the authorized user's calendar. If no events are found an
* appropriate message is printed.
*/
function listUpcomingEvents() {
gapi.client.calendar.events.list({
'calendarId': 'nfl_15_%4diami+%44olphins#sports#group.v.calendar.google.com',
'timeMin': (new Date()).toISOString(),
'showDeleted': false,
'singleEvents': true,
'maxResults': 10,
'orderBy': 'startTime'
}).then(function(response) {
var events = response.result.items;
appendPre('Upcoming events:');
// console.log(events);
function myFunction() {
var cal = CalendarApp.getCalendarById(id);
var events = cal.getEvents(startTime, endTime);
for ( var i in events ) {
var id = events[i].getId();
}
}
if (events.length > 0) {
for (i = 0; i < events.length; i++) {
var event = events[i];
var when = event.start.dateTime;
if (!when) {
when = event.start.date;
}
appendPre(event.summary + ' (' + when + ')')
}
} else {
appendPre('No upcoming events found.');
}
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
with this format:
Dolphins # Jets (2020-11-29T19:00:00+01:00)
Bengals # Dolphins (2020-12-06T19:00:00+01:00)
Chiefs # Dolphins (2020-12-13T19:00:00+01:00)
Patriots # Dolphins (2020-12-20T19:00:00+01:00)
Dolphins # Raiders (2020-12-27T18:00:00+01:00)
Dolphins # Bills (2021-01-03T19:00:00+01:00)
I want to get only one specific event date for example the Dolphin # Jets and inserting this date and time as input for the following javascript countdown:
// dolphin # Jets
var countDownDate = new Date("nov 19, 2020 19:00:00").getTime();
The javascript accepts only the format ("mmm dd, yyyy hh:mm:ss") as far as I know.
Now, I appreciate if someone can tell me if is it even achievable or giving me a direction to achieve the same results in some other way.
Thanks in advance,
Cesare
As you may already know by now, Google Calendar time format uses RFC3339:
https://validator.w3.org/feed/docs/error/InvalidRFC3339Date.html
If you are enquiring about converting Google Calendar time format to ("mmm dd, yyyy hh:mm:ss") format: You can use a date helper library like moment.js:
Look at this tutorial:
https://flaviocopes.com/momentjs/
And then do something like:
<script type="text/javascript" src="https://unpkg.com/moment"></script>
<script>
// Following I am obtaining the milliseconds date, then performing the moment format on the milliseconds, but you can use the moment library per your needs
const millisecsDate = Date.parse('2020-11-29T19:00:00+01:00');
const date = moment(millisecsDate).format("MMM DD, YYYY hh:mm:ss") ;
console.log(date);
</script>
Replace the CLIENT_ID and the API_KEY in the code, you should enter your calendar id in the code for now I set the calendar id to 'primary'
I added input text to enter the desired event summary (Title of the event) to look up it's event start time
When click authorize it will fetch the target event from the desired calendar id you entered in your code. Mainly it fetches all the upcoming events for the given calendar and checks each event summary against the entered desired summary and when it finds the event it displays and stores the corresponding event's event.start.dateTime to var countDownDate (part 1). The reason I did not use a direct get because it uses calendar id and event id and the event id is not accessible programmatically unless you do another lookup per the summary or manually check it in google calendar application in the events settings
I added a function for the date time formatting from the google calendar time format to the desired "mmm dd, yyyy hh:mm:ss" format (part2)
Not sure what you need to do exactly with the countDownDate; example start a timer before the event start date by 60 minutes? and display the count down? or something like that...?
Check this code (but replace CLIENT_ID and the API_KEY as mentioned above):
<!DOCTYPE html>
<html>
<head>
<title>Google Calendar API Quickstart</title>
<meta charset="utf-8" />
</head>
<body>
<p>Google Calendar API Quickstart</p>
<!--Add buttons to initiate auth sequence and sign out-->
<label id="lookup_label" for="event_name_txt"> Enter Event Summary/Name to look for in the calendar</label>
<input id="event_name_txt" type="text" placeholder = "Event name to look for" style="display: none;"/>
<button id="authorize_button" style="display: none;">Authorize</button><br>
<button id="lookup_button" style="display: none;">Lookup Event</button><br>
<button id="signout_button" style="display: none;">Sign Out</button>
<pre id="content" style="white-space: pre-wrap;"></pre>
<script type="text/javascript" src="https://unpkg.com/moment"></script>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = 'Your CLIENT_ID ';
var API_KEY = 'Your API_KEY';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/calendar.readonly";
// Holder for the format "mmm dd, yyyy hh:mm:ss"
var countDownDate;
var authorizeButton = document.getElementById('authorize_button');
var signoutButton = document.getElementById('signout_button');
var lookupButton = document.getElementById('lookup_button');
var desiredEvent = document.getElementById('event_name_txt');
var lookupLabel = document.getElementById('lookup_label');
var pre = document.getElementById('content');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
apiKey: API_KEY,
clientId: CLIENT_ID,
discoveryDocs: DISCOVERY_DOCS,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
lookupButton.onclick = handleLookupClick;
}, function(error) {
appendPre(JSON.stringify(error, null, 2));
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
lookupButton.style.display = 'block';
desiredEvent.style.display = 'block';
lookupLabel.style.display = 'block';
pre.style.display = 'block';
//listUpcomingEvents();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
lookupButton.style.display = 'none';
desiredEvent.style.display = 'none';
lookupLabel.style.display = 'none';
pre.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
function handleLookupClick (event){
listUpcomingEvents();
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* #param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
pre.textContent = 'Desired Event:';
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
function formatTime(time){
const millisecsDate = Date.parse(time);
return moment(millisecsDate).format("MMM DD, YYYY hh:mm:ss") ;
}
/**
* Print the summary and start datetime/date of the next ten events in
* the authorized user's calendar. If no events are found an
* appropriate message is printed.
*/
function listUpcomingEvents() {
gapi.client.calendar.events.list({
'calendarId': 'primary',
'timeMin': (new Date()).toISOString(),
'showDeleted': false,
'singleEvents': true,
'maxResults': 10,
'orderBy': 'startTime'
}).then(function(response) {
var events = response.result.items;
// appendPre('Upcoming events:');
var foundTargetEvent = false;
if (events.length > 0) {
for (i = 0; i < events.length; i++) {
var event = events[i];
<!-- var when = event.start.datetime; -->
<!-- if (!when) { -->
<!-- when = event.start.date; -->
<!-- } -->
if (event.summary === desiredEvent.value)
{
// appendPre('Desired Event:');
foundTargetEvent = true;
var when = event.start.dateTime;
if (!when) {
when = event.start.date;
}
countDownDate = formatTime(when);
//console.log(countDownDate);
appendPre(event.summary + ' (' + when + ')' + ' Formated Time = ' + countDownDate);
}
}
if (!foundTargetEvent){
appendPre(' No event found in the calendar with this title/summary');
}
} else {
appendPre('No upcoming events found.');
}
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>

Google calendar api JS doesnt work

I use code from official tutorial:
<html>
<head>
<title>Google Calendar API Quickstart</title>
<meta charset='utf-8' />
</head>
<body>
<!--Add buttons to initiate auth sequence and sign out-->
<button id="authorize-button" style="display: none;">Authorize</button>
<button id="signout-button" style="display: none;">Sign Out</button>
<pre id="content"></pre>
<script type="text/javascript">
// Client ID and API key from the Developer Console
var CLIENT_ID = '930775442242-5dutsv4pa4ibr23c650rcs4upo3v7qad.apps.googleusercontent.com';
// Array of API discovery doc URLs for APIs used by the quickstart
var DISCOVERY_DOCS = ["https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest"];
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
var SCOPES = "https://www.googleapis.com/auth/calendar.readonly";
var authorizeButton = document.getElementById('authorize-button');
var signoutButton = document.getElementById('signout-button');
/**
* On load, called to load the auth2 library and API client library.
*/
function handleClientLoad() {
gapi.load('client:auth2', initClient);
}
/**
* Initializes the API client library and sets up sign-in state
* listeners.
*/
function initClient() {
gapi.client.init({
discoveryDocs: DISCOVERY_DOCS,
clientId: CLIENT_ID,
scope: SCOPES
}).then(function () {
// Listen for sign-in state changes.
gapi.auth2.getAuthInstance().isSignedIn.listen(updateSigninStatus);
// Handle the initial sign-in state.
updateSigninStatus(gapi.auth2.getAuthInstance().isSignedIn.get());
authorizeButton.onclick = handleAuthClick;
signoutButton.onclick = handleSignoutClick;
});
}
/**
* Called when the signed in status changes, to update the UI
* appropriately. After a sign-in, the API is called.
*/
function updateSigninStatus(isSignedIn) {
if (isSignedIn) {
authorizeButton.style.display = 'none';
signoutButton.style.display = 'block';
listUpcomingEvents();
} else {
authorizeButton.style.display = 'block';
signoutButton.style.display = 'none';
}
}
/**
* Sign in the user upon button click.
*/
function handleAuthClick(event) {
gapi.auth2.getAuthInstance().signIn();
}
/**
* Sign out the user upon button click.
*/
function handleSignoutClick(event) {
gapi.auth2.getAuthInstance().signOut();
}
/**
* Append a pre element to the body containing the given message
* as its text node. Used to display the results of the API call.
*
* #param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('content');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
/**
* Print the summary and start datetime/date of the next ten events in
* the authorized user's calendar. If no events are found an
* appropriate message is printed.
*/
function listUpcomingEvents() {
gapi.client.calendar.events.list({
'calendarId': 'primary',
'timeMin': (new Date()).toISOString(),
'showDeleted': false,
'singleEvents': true,
'maxResults': 10,
'orderBy': 'startTime'
}).then(function(response) {
var events = response.result.items;
appendPre('Upcoming events:');
if (events.length > 0) {
for (i = 0; i < events.length; i++) {
var event = events[i];
var when = event.start.dateTime;
if (!when) {
when = event.start.date;
}
appendPre(event.summary + ' (' + when + ')')
}
} else {
appendPre('No upcoming events found.');
}
});
}
</script>
<script async defer src="https://apis.google.com/js/api.js"
onload="this.onload=function(){};handleClientLoad()"
onreadystatechange="if (this.readyState === 'complete') this.onload()">
</script>
</body>
</html>
Therea are two buttons for sign in and for sign out.
Problem: this code doesn't work in firefox (when I click auth button, choose google account then nothing happens) and in chrome (I cant logout).
Maybe there is any error in this code?
How can I solve this problem?
In my console there are not any errors.
Thanks,
For the signing-out process try using GoogleAuth.disconnect(); to revoke the token which was mentioned here.
The calendar API sample is working as intended on my end. Make sure it's enabled in your Google Dev console and the localhost ports are indicated in your clientID

Categories