Google provides a friendly .html code in https://developers.google.com/identity/sign-in/web I tried this code in a .html file and it works totally fine. After the user is signed in, onSignin would be revoked every time the page is loaded, which means user info will be logged in console But if I use this code in a nuxt component, only the sign-in process would be run, onSignIn function is not revoked, and no errors were shown. Here's my code:
<template>
<div class="g-signin2" data-onsuccess="onSignIn"></div>
</template>
<script>
/* eslint-disable */
function onSignIn(googleUser) {
// Useful data for your client-side scripts:
var profile = googleUser.getBasicProfile()
console.log('ID: ' + profile.getId()) // Don't send this directly to your server!
console.log('Full Name: ' + profile.getName())
console.log('Given Name: ' + profile.getGivenName())
console.log('Family Name: ' + profile.getFamilyName())
console.log('Image URL: ' + profile.getImageUrl())
console.log('Email: ' + profile.getEmail())
// The ID token you need to pass to your backend:
var id_token = googleUser.getAuthResponse().id_token
console.log('ID Token: ' + id_token)
}
export default {
head() {
return {
meta: [
{
name: 'google-signin-scope',
content: 'profile email'
},
{
name: 'google-signin-client_id',
content: process.env.GOOGLE_CLIENT_ID
}
],
script: [
{
src: 'https://apis.google.com/js/platform.js',
defer: true,
async: true
}
]
}
}
}
</script>
I'm sure process.env.GOOGLE_CLIENT_ID is correct since I've checked dom tree when running on browser. If you know where the bug is please let me know, thank you.
Vue SFC's script is isolated, and you have declared onSignIn
just in this scope. Yeah, this is not going to fly.
Luckily, you can simply add onSignIn
function in window
scope:
window.onSignIn = onSignIn
Mostly, you've got it all right. But there is even dedicated package ready for this use case: google-signin-vue. I would not recommend blindly using it though; instead look at source code and find features you'd like to have, if needed.