Recalling Authorization for Google Calendar API with Javascript

Referencing the code found at: https://developers.google.com/calendar/api/quickstart/js

The documentation explains that "Authorization information is stored in the file system, so the next time you run the sample code, you aren't prompted for authorization."

However, I am required to request permission every time I reload the webpage. Any suggestions?

const CLIENT_ID = '';
const API_KEY = '';

const DISCOVERY_DOC = 'https://www.googleapis.com/discovery/v1/apis/calendar/v3/rest';
const SCOPES = 'https://www.googleapis.com/auth/calendar.readonly https://www.googleapis.com/auth/calendar';

let tokenClient;
let gapiInited = false;
let gisInited = false;

function gapiLoaded() {
  gapi.load('client', initializeGapiClient);
}

async function initializeGapiClient() {
  await gapi.client.init({
    apiKey: API_KEY,
    discoveryDocs: [DISCOVERY_DOC],
  });
  gapiInited = true;
}

function gisLoaded() {
  tokenClient = google.accounts.oauth2.initTokenClient({
    client_id: CLIENT_ID,
    scope: SCOPES,
    callback: '', // defined later
  });
  gisInited = true;
}

//? Sign In
function handleAuthClick() {
  tokenClient.callback = async (resp) => {
    if (resp.error !== undefined) {
      throw (resp);
    }
  };

  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
function handleSignoutClick() {
  console.log("sign in")
  const token = gapi.client.getToken();
  if (token !== null) {
    google.accounts.oauth2.revoke(token.access_token);
    gapi.client.setToken('');
  }
}

Answer №1

Indeed, buried within the depths of the Javascript quick start guide for Google Calendar, a curious statement awaits.

The authorization information is supposedly nestled snugly in the file system, ensuring a seamless experience upon subsequent runs of the sample code.

However, this claim does not hold water for the Javascript sample, tailored specifically for web applications. It appears to be an oversight on the part of the creators, and I have duly brought it to their attention.

In contrast, the Node.js sample follows through on its promise, housing the authorization info in the filesystem as intended for installed applications. Perhaps a simple case of miscommunication or oversight during the drafting process.

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

How to Include a JavaScript File from a Local Source on a Web Page

Is the process for adding a script with document.createElement('script') the same when it comes to a local file? I've experimented with using function.toString() calls, but it's not very efficient. I would prefer to store the necessary ...

Issue with Magento: Unable to execute dataflow profiles due to Ajax Error (Uncaught TypeError: e is not a function)

Whenever I try to execute a dataflow profile in Magento, the following series of events unfold: The CSV file is uploaded successfully X rows are found A message displays: Starting ... :: saveRow (handler-method) However, a JavaScript error interrupts th ...

What is the method for viewing the available choices in a select2 instance?

I am trying to retrieve the options configured in a select2 instance, specifically the value of the allowClear option whether it is true or false. Upon exploring the object, I located the allowClear option in jQuery... -> select2 -> options -&g ...

AngularJS filter that retrieves only values that have an exact match

In my AngularJS application, I have a checkbox that acts as a filter: Here is the data being used: app.controller('listdata', function($scope, $http) { $scope.users = [{ "name": "pravin", "queue": [{ "number": "456", "st ...

Display a tooltip when the cursor hovers close to a line in D3 visualizations

Currently, I have a D3js line chart with SVG circles added to the points. When users hover over these circles, they can see a tooltip. https://i.sstatic.net/kYpeg.png https://jsfiddle.net/jhynag08/38/ However, I would like the tooltip to appear when user ...

Utilizing AJAX to dynamically update div content within an overlay

Can someone please help me figure out what is going on with my code. I have 3 links, each with a data-action and an ID number. When I click on the links, nothing happens. It seems like it's not fetching the data from my ajax request (action.php). H ...

Position a dynamic <div> in the center of the screen

My goal is to design a gallery page with a list of thumbnails, where clicking on a thumbnail will open the related image in a popup div showing its full size. The issue I'm facing is how to center the popup div on the screen, especially when each pic ...

Establish the date input format specifically for vue-moment

I've been trying to use vue-moment for date formatting in my application, but I'm having trouble getting it to recognize the input format that moment.js should parse. The date format returned by my API is like this: 2019-01-01 24:00:00 GMT Here ...

Menu only appears with a double click on the label button

Currently, I'm facing an issue where I have to click the label "button" (hamburger menu) twice in order to show the menu for the second time. My belief is that there might be a conflict between CSS and jQuery causing this behavior. The desired funct ...

Tips for detecting when a user unexpectedly leaves an ASP.Net page

Is there a way to notify users when they are leaving my ASP.Net page without triggering a warning when they click the save button? I've been reading several articles on this topic, but being new to it all has left me confused. The suggested solution ...

Incorporating middleware through app.use functionality

Can you explain the difference between the following code snippets: function setLocale(req, res, next) { req.params.locale = req.params.locale || 'pt'; res.cookie('locale', req.params.locale); req.i18n.setLocale(req.params ...

Guide for incorporating a clickable link into a specific section of a component

I am working with a File component and displaying the name of the file. I would like to add a clickable link to it. if (item.type === "file") { return ( <File name={item.name} /> // I would like to link item.url to this item.na ...

What is the best way to retrieve the response from an Observable/http/async call in Angular?

My service returns an observable that makes an http request to my server and receives data. However, I am consistently getting undefined when trying to use this data. What could be causing this issue? Service: @Injectable() export class EventService { ...

Retrieving and assigning data values within an Angular JS service

Here is the service I created to fetch user details: angular.module('app') .factory('userDetailService', function($http) { var userData = {}; function getUserDetails(userId) { if (userId) { return $http.get ...

Alter the color scheme using jQuery

Exploring the world of websites, I've come across many with a unique color switch feature. Users have the ability to choose a color, and the entire page transforms to match their selection. Check out these links for some examples... http://csmthe ...

Tips and tricks for manipulating base64 images in Node.js

I have a unique challenge - I want to manipulate a base64 picture by adding just one extra pixel. My goal is to send a base64 image string (e.g. data:image/png;base64,iVBORw0KG...) from my express server. Let's say the image is 100x100px and I need to ...

Tips for rearranging array position retrieved from API in Vue.js

props: { groups: Array, }, computed: { groups: function(arr) { alert('hi') } }, <div v-for="(item, index) in groups" :key="item.id" :id="item.id" class="group-name" @click="isOnlySelected ? null : $emit('setSele ...

JS animation triumphant

I have developed an app that utilizes a checkbox to control the appearance of an overlay on a screen. To ensure smooth transitions, I have incorporated animations into the process. #overlay{ position:absolute; height: 100vh; width: 100vw; ...

Tips for integrating a logo into router view animations

How can I incorporate a logo into the white fade-in screen that appears when navigating between subpages using <router-view> within App.vue? Here is a simplified version of my App.vue code: <template> <div id="app"> <div ...

Is there a way to automatically fill in a MUI textfield in a React Hook form with data retrieved from Firestore?

Utilizing React Hook Forms alongside MUI TextField components has been a productive challenge for me. I've been able to successfully fetch data from Firestore and aim to prefill the form with this retrieved information. Although I am employing useFor ...