gpt4 book ai didi

javascript - 如何更改 Google 登录以显示个人资料信息而不是 console.log

转载 作者:行者123 更新时间:2023-12-03 04:34:59 26 4
gpt4 key购买 nike

我已经使用 Google 提供的教程在我的网站上实现了 Google 登录。但是,我不想将配置文件信息存储在 console.log 中,而是想将其显示在我的网页上。这是我目前拥有的代码:

<div class="g-signin2" data-onsuccess="onSignIn"></div>
<script>
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
console.log("ID: " + profile.getId());
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());
};
</script>

如何更改此设置?

最佳答案

首先,如果您还没有这样做,您需要从 Creating a Google API Console project and client ID 开始.

如果您已经这样做了,请继续将必要的代码嵌入到您的 HTML 中。为此,您首先必须通过在 <head> 之间添加此行来引用 Google Platform。和</head>标签。

    <script src="https://apis.google.com/js/platform.js" async defer></script>

然后在 <body> 之间插入下面代码和</body>标签。

<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>

现在是时候调用该函数并将用户数据分配给 HTML 了。将这些行添加到 <script></script><body> 内的标签

NOTE: You may call it from another file, but i am not going to mention it here.

  <script>
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
var data = '';
data += '<ul>';
data += '<li><img src="' + profile.getImageUrl() + '"/></li>';
data += '<li>ID: ' + profile.getId() + '</li>';
data += '<li>Full Name: ' + profile.getName() + '</li>';
data += '<li>Given Name: ' + profile.getGivenName() + '</li>';
data += '<li>Family Name: ' + profile.getFamilyName() + '</li>';
data += '<li>Email: ' + profile.getEmail() + '</li>';
data += '</ul>';
document.getElementsByClassName("aClassOfYourOwn")[0].innerHTML =data;
};
</script>

NOTE 2: This is only one way of handling this, as you may assign new variables, and call them anywhere you like, but this is only for starter.

现在,是时候创建一个新的 div 了。这样您就可以使用从 Google 获得的信息。因此,为了做到这一点,请在您的 <body> 中添加此行标签。

<div class="aClassOfYourOwn"></div>

也许就在之后

<div class="g-signin2" data-onsuccess="onSignIn" data-theme="dark"></div>

这取决于你。最后,如果您想添加注销选项,请在 <body> 中添加此行标签。

<a href="#" onclick="signOut();">Sign out</a>

当然,正如您可能已经看到的,我们没有声明一个名为 signOut() 的函数。 。那么我们就去声明吧。

<script>
function signOut() {
var auth2 = gapi.auth2.getAuthInstance();
auth2.signOut().then(function () {
console.log('User signed out.');
var data = 'There is no user signed in';
document.getElementsByClassName("g-signin3")[0].innerHTML =data;
});
}
</script>

这仅用于演示。当然,向用户显示用户数据是没有意义的。但你可以用它做的事情是无限的。例如,您可以获取 ID 并将用户引导至各自的页面。

关于javascript - 如何更改 Google 登录以显示个人资料信息而不是 console.log,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43333027/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com