阿尔卑斯丶
圣骑士
圣骑士
  • 最后登录2023-11-03
  • 发帖数59
  • 社区居民
  • 原创写手
阅读:656回复:0

[vue]第三方登录(谷歌)

楼主#
更多 发布于:2023-07-17 22:09
首先是需要加载google的sdk
按照网上其他教程可以是在index.html中全局中增加一个script标签,但是一般不是在登录页面不需要,所以我是在登录页面进行加载的。
加载sdk的代码如下:

const script1 = document.createElement('script');
script1.src = 'https://accounts.google.com/gsi/client';
script1.async = true;
script1.defer = true;
然后需要在页面上找个元素进行点击,这里谷歌会自己生成一个iframe,这里的样式不是太好自定义到UI设计的样式,采用最笨的办法,将这里的按钮设置到和我们页面上写的页面元素一样大,然后设置透明。
首先是js,我们需要获取一个client id
const gClientId = 'xxxxxxx.apps.googleusercontent.com'
然后将我们的script标签append到页面元素上


document.getElementById('googleBtn').appendChild(script1);
然后是加载部分
if(window.google && window.google.accounts){
    console.log('加载sdk完成')
    window.google.accounts.id.initialize({
        client_id: gClientId,
        callback: this.handleCredentialResponse,
        auto_select: true
    })
    window.google.accounts.id.renderButton(
        this.$refs.googleLoginBtn, {}
    )
}else{
    setTimeout(()=>{
        console.log('重新加载资源')
        if(window.google && window.google.accounts){
            window.google.accounts.id.initialize({
                client_id: gClientId,
                callback: this.handleCredentialResponse,
                auto_select: true
            })
            window.google.accounts.id.renderButton(
                this.$refs.googleLoginBtn, {}
            )
        }else{
            console.log('加载失败')
        }
    },3000)
}
接下来就是谷歌登录的handleCredentialResponse函数
函数的参数接受一个response,是谷歌那边返回的内容
里边包含一个credential参数,将这个参数传递给后端,手段通过谷歌方法进行解析可以获得用户信息以进行登录操作。

最新喜欢:

doubleyongdouble...
游客


返回顶部

公众号

公众号