我正在尝试在我的网络应用程序上实现 Google 登录。
我可以看到弹出窗口,要求我授权该应用程序。但是,当调用 onSignIn 时,我收到:
googleUser.getBasicProfile is not a function
我不太确定为什么?任何帮助将不胜感激。
代码:
索引.html:
<span id="signinButton">
<span
class="g-signin"
data-callback="onSignIn"
data-clientid="myidHere"
data-cookiepolicy="single_host_origin"
data-requestvisibleactions="http://schemas.google.com/AddActivity"
data-scope="https://www.googleapis.com/auth/plus.login">
</span>
app.js
function onSignIn(googleUser) {
var profile = googleUser.getBasicProfile();
console.log('ID: ' + profile.getId()); // Do not send to your backend! Use an ID token instead.
console.log('Name: ' + profile.getName());
console.log('Image URL: ' + profile.getImageUrl());
console.log('Email: ' + profile.getEmail());
var id_token = googleUser.getAuthResponse().id_token;
}
(function() {
var po = document.createElement('script'); po.type = 'text/javascript'; po.async = true;
po.src = 'https://apis.google.com/js/client:plusone.js';
var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(po, s);
})();
这里我的工作是使用新的 GSI(Google Sign Identity)登录后获取用户信息。测试日期:2024 年 5 月 2 日
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Login</title>
</head>
<body>
<script src="https://accounts.google.com/gsi/client" async defer></script>
<div id="mybtn"></div>
<script>
function handleCredentialResponse(googleUser) {
// console.log("Encoded JWT ID token: " + googleUser.credential);
const tokens = googleUser.credential.split(".");
const responsePayload = JSON.parse(atob(tokens[1]));
console.log("ID: " + responsePayload.sub);
console.log('Full Name: ' + responsePayload.name);
console.log('Given Name: ' + responsePayload.given_name);
console.log('Family Name: ' + responsePayload.family_name);
console.log("Image URL: " + responsePayload.picture);
console.log("Email: " + responsePayload.email);
// cache the jwt token into cookie for 1 hour to be reused later
// Get current time
var now = new Date();
// Set expiration time to 1 hour from now
var expirationTime = new Date(now.getTime() + 1 * 3600 * 1000); // 1 hour = 3600 seconds * 1000 milliseconds
// Construct the cookie string
var cookieString = "user_jwt=" + encodeURIComponent(tokens[1]) + "; expires=" + expirationTime.toUTCString() + "; path=/";
// Set the cookie
document.cookie = cookieString;
}
window.onload = function() {
google.accounts.id.initialize({
client_id: "GOOGLE-ID.apps.googleusercontent.com",
callback: handleCredentialResponse
});
google.accounts.id.renderButton(
document.getElementById("mybtn"), {
theme: "outline",
size: "large"
} // customization attributes
);
google.accounts.id.prompt(); // also display the One Tap dialog
}
</script>
</body>
</html>