[Vuejs]-Recreating JavaScript Google Calendar API authentication in Vue

1👍

You are loading the gsi script in your index.html and calling initClient in the onload function. It’s obvious that there’s no way Vue will call your initClient function from index.html as this function is defined in your component. So:

  • Remove script tag from index.html
  • Load the gsi script in your Vue component
  • (Bonus) add a check in your component to only render buttons if the client is loaded.

Updated Code (comments added):

<template>
  <h1>Google Identity Services Authorization Token model</h1>

  <!-- Here we are going to restrict buttons until our client is loaded -->
  <template v-if="!client">
    <button @click="getToken()">Get access token</button><br /><br />
    <button @click="loadCalendar()">Load Calendar</button><br /><br />
    <button @click="revokeToken()">Revoke token</button>
  </template>
  <span v-else>Loading Google APIs</span>
</template>

<script>
export default {
  // Move the variables in data
  data() {
    return {
      client: null,
      access_token: null,
    };
  },
  methods: {
    initClient() {
      // Update reference from client to this.client
      this.client = google.accounts.oauth2.initTokenClient({
        client_id: "...",
        scope:
          "https://www.googleapis.com/auth/calendar.readonly \
           https://www.googleapis.com/auth/contacts.readonly",
        callback: (tokenResponse) => {
          // Update reference from access_token to this.access_token
          this.access_token = tokenResponse.access_token;
        },
      });
    },
    getToken() {
      // Update reference from client to this.client
      this.client.requestAccessToken();
    },
    revokeToken() {
      // Update reference from access_token to this.access_token
      google.accounts.oauth2.revoke(this.access_token, () => {
        console.log("access token revoked");
      });
    },
    loadCalendar() {
      var xhr = new XMLHttpRequest();
      xhr.open("GET", "https://www.googleapis.com/calendar/v3/calendars/primary/events");
      // Update reference from access_token to this.access_token
      xhr.setRequestHeader("Authorization", "Bearer " + this.access_token);
      xhr.send();
    },
    
    // Here we are loading the script
    loadGsiScript() {
      const gsiScript = document.createElement("script");
      gsiScript.src = "https://accounts.google.com/gsi/client";
      gsiScript.async = true;
      gsiScript.defer = true;

      // We need to link our initClient here
      gsiScript.onload = this.initClient;
      document.head.appendChild(gsiScript);
    },
  },

  // Once HTML document is ready Vue will call our loadGsiScript function
  mounted() {
    this.loadGsiScript();
  },
};
</script>
👤U-Dev

Leave a comment