Skip to content
Advertisement

How to use Google Identity Services JavaScript SDK with Vue / TypeScript?

I’m trying to authorize some Google APIs using the new Google Identity Services JavaScript SDK in my Vue / Quasar / TypeScript app.

As per the docs I have loaded the Google 3P Authorization JavaScript Library in the header of my index.template.HTML file like so:

<script src="https://accounts.google.com/gsi/client" onload="console.log('TODO: add onload function')">  
</script>

Now inside a Vue component I have this:

<template>
  <v-btn
    class="q-ma-md"
    design="alpha"
    label="Connect Google Calendar"
    @click="handleGoogleCalendarConnect"
  />
</template>

<script setup lang="ts">
import VBtn from 'src/components/VBtn.vue';

const client = google.accounts.oauth2.initCodeClient({ // <-- TypeScript Error Here
  client_id:
    'MY_CLIENT_API_KEY_GOES_HERE',
  scope: 'https://www.googleapis.com/auth/calendar.readonly',
  ux_mode: 'popup',
  callback: (response: any) => {
    const xhr = new XMLHttpRequest();
    xhr.open('POST', code_receiver_uri, true);
    xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
    // Set custom header for CRSF
    xhr.setRequestHeader('X-Requested-With', 'XmlHttpRequest');
    xhr.onload = function () {
      console.log('Auth code response: ' + xhr.responseText);
    };
    xhr.send('code=' + code);
  },
});

const handleGoogleCalendarConnect = () => {
  client.requestCode();
};
</script>

But I am getting a TypeScript error on “google” that says: Cannot find name 'google'. ts(2304)

Maybe it’s because I’m missing types for the Google Identity Services JavaScript SDK? If so, where to find them?

Or perhaps the problem is something else?

Advertisement

Answer

Found the correct type package:

npm i @types/google.accounts

This removes the error.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement