Google calendar api JS doesnt work - javascript

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

Related

Google sign in asks sign in again after page refresh

index.html
When I click Authorize, Google signs in, but when I refresh the page, it prompts me to sign in to Google once more. What can I do to stay signed in until the user signs out? Here I tried javascript calendar API to insert an event into Google Calendar.
I'm using the Google Calendar API and I'm trying to keep the user signed in when they reload the page but I'm having trouble with it. I can't find anything online about this.
<!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" onclick="handleAuthClick()">Authorize</button>
<button id="signout_button" onclick="handleSignoutClick()">Sign Out</button>
<button id="addto_cal" onclick="addto_cal()">Add to calendar</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 = 'my_client_id';
const API_KEY = 'my_api_key';
// Discovery doc URL for APIs used by the quickstart
const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest';
// Authorization scopes required by the API; multiple scopes can be
// included, separated by spaces.
const SCOPES = 'https://www.googleapis.com/auth/calendar';
let tokenClient;
let gapiInited = false;
let gisInited = false;
document.getElementById('authorize_button').style.visibility = 'hidden';
document.getElementById('signout_button').style.visibility = 'hidden';
document.getElementById('addto_cal').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';
document.getElementById('addto_cal').style.visibility = 'visible';
//window.location.replace("success_user.jsp");
//window.history.pushState('page2', 'Title', 'inbetween.jsp');
await listUpcomingEvents();
};
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';
document.getElementById('addto_cal').style.visibility = 'hidden';
}
}
function addto_cal()
{
try {
var resource = {
"summary": "Vimal Bus Booking",
"location": "Chennai",
'description': "Trichy to Chennai at 9:00 PM",
"start": {
"dateTime": "2022-08-30T10:00:00.000-07:00"
},
"end": {
"dateTime": "2022-09-01T10:25:00.000-07:00"
}
};
var request = gapi.client.calendar.events.insert({
'calendarId': 'primary',
'resource': resource
});
request.execute(function(resp) {
console.log(resp);
});
}
catch (err) {
document.getElementById('content').innerText = err.message;
return;
}
}
/**
* 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.
*/
async function listUpcomingEvents() {
let response;
try {
const request = {
'calendarId': 'primary',
'timeMin': (new Date()).toISOString(),
'showDeleted': false,
'singleEvents': true,
'maxResults': 10,
'orderBy': 'startTime',
};
response = await gapi.client.calendar.events.list(request);
} catch (err) {
document.getElementById('content').innerText = err.message;
return;
}
const events = response.result.items;
if (!events || events.length == 0) {
document.getElementById('content').innerText = 'No events found.';
return;
}
// Flatten to string to display
const output = events.reduce(
(str, event) => `${str}${event.summary} (${event.start.dateTime || event.start.date})\n`,
'Events:\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>
Technically you can't stay signed in after the page reload - all state data is lost, so JS code have to redo all process of sign-in.
But to make life easier you can somehow save access token and use it to speed-up things after page reload. That's what Google lib should do behind scenes - save to cookies or something like that. And it looks like it fails to do so in your case, because of browser or Google security policy, some privacy tool, bug - there are many possible reasons. Did you check browser console for errors?

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 classroom api to create a course using js

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.

Uncaught TypeError: Cannot read property 'length' of undefined Google Calendar API

I am using this simple google calendar API javascriptI have not changed the code given in the tutorial except adding my client ID
<html>
<head>
<script type="text/javascript">
// Your Client ID can be retrieved from your project in the Google
// Developer Console, https://console.developers.google.com
var CLIENT_ID = 'id';
var SCOPES = ["https://www.googleapis.com/auth/calendar.readonly"];
/**
* Check if current user has authorized this application.
*/
function checkAuth() {
gapi.auth.authorize(
{
'client_id': CLIENT_ID,
'scope': SCOPES,
'immediate': true
}, handleAuthResult);
}
/**
* Handle response from authorization server.
*
* #param {Object} authResult Authorization result.
*/
function handleAuthResult(authResult) {
var authorizeDiv = document.getElementById('authorize-div');
if (authResult && !authResult.error) {
// Hide auth UI, then load client library.
authorizeDiv.style.display = 'none';
loadCalendarApi();
} else {
// Show auth UI, allowing the user to initiate authorization by
// clicking authorize button.
authorizeDiv.style.display = 'inline';
}
}
/**
* Initiate auth flow in response to user clicking authorize button.
*
* #param {Event} event Button click event.
*/
function handleAuthClick(event) {
gapi.auth.authorize(
{client_id: CLIENT_ID, scope: SCOPES, immediate: false},
handleAuthResult);
return false;
}
/**
* Load Google Calendar client library. List upcoming events
* once client library is loaded.
*/
function loadCalendarApi() {
gapi.client.load('calendar', 'v3', listUpcomingEvents);
}
/**
* 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() {
var request = gapi.client.calendar.events.list({
'calendarId': 'primary',
'timeMin': (new Date()).toISOString(),
'showDeleted': false,
'singleEvents': true,
'maxResults': 10,
'orderBy': 'startTime'
});
request.execute(function(resp) {
var events = resp.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.');
}
});
}
/**
* Append a pre element to the body containing the given message
* as its text node.
*
* #param {string} message Text to be placed in pre element.
*/
function appendPre(message) {
var pre = document.getElementById('output');
var textContent = document.createTextNode(message + '\n');
pre.appendChild(textContent);
}
</script>
<script src="https://apis.google.com/js/client.js?onload=checkAuth">
</script>
</head>
<body>
<div id="authorize-div" style="display: none">
<span>Authorize access to Google Calendar API</span>
<!--Button for the user to click to initiate auth sequence -->
<button id="authorize-button" onclick="handleAuthClick(event)">
Authorize
</button>
</div>
<pre id="output"></pre>
</body>
</html>
I do not understand how to debug google app scripts in a browser. Any help is appreciated.

Categories