Интеграция входа в Google с использованием прослушивателей
Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
Прослушиватели предоставляют возможность автоматически реагировать на изменения в сеансе входа текущего пользователя. Например, после того, как ваш метод запуска инициализирует объект auth2 для входа в Google, вы можете настроить прослушиватели для реагирования на такие события, как изменения состояния auth2.isSignedIn
или изменения в auth2.currentUser
.
Следующий код демонстрирует использование клиентского метода listen()
версии 2.0 для реагирования на изменения в auth2.isSignedIn
и auth2.currentUser
.
var auth2; // The Sign-In object.
var googleUser; // The current user.
/**
* Calls startAuth after Sign in V2 finishes setting up.
*/
var appStart = function() {
gapi.load('auth2', initSigninV2);
};
/**
* Initializes Signin v2 and sets up listeners.
*/
var initSigninV2 = function() {
auth2 = gapi.auth2.init({
client_id: 'CLIENT_ID.apps.googleusercontent.com',
scope: 'profile'
});
// Listen for sign-in state changes.
auth2.isSignedIn.listen(signinChanged);
// Listen for changes to current user.
auth2.currentUser.listen(userChanged);
// Sign in the user if they are currently signed in.
if (auth2.isSignedIn.get() == true) {
auth2.signIn();
}
// Start with the current live values.
refreshValues();
};
/**
* Listener method for sign-out live value.
*
* @param {boolean} val the updated signed out state.
*/
var signinChanged = function (val) {
console.log('Signin state changed to ', val);
document.getElementById('signed-in-cell').innerText = val;
};
/**
* Listener method for when the user changes.
*
* @param {GoogleUser} user the updated user.
*/
var userChanged = function (user) {
console.log('User now: ', user);
googleUser = user;
updateGoogleUser();
document.getElementById('curr-user-cell').innerText =
JSON.stringify(user, undefined, 2);
};
/**
* Updates the properties in the Google User table using the current user.
*/
var updateGoogleUser = function () {
if (googleUser) {
document.getElementById('user-id').innerText = googleUser.getId();
document.getElementById('user-scopes').innerText =
googleUser.getGrantedScopes();
document.getElementById('auth-response').innerText =
JSON.stringify(googleUser.getAuthResponse(), undefined, 2);
} else {
document.getElementById('user-id').innerText = '--';
document.getElementById('user-scopes').innerText = '--';
document.getElementById('auth-response').innerText = '--';
}
};
/**
* Retrieves the current user and signed in states from the GoogleAuth
* object.
*/
var refreshValues = function() {
if (auth2){
console.log('Refreshing values...');
googleUser = auth2.currentUser.get();
document.getElementById('curr-user-cell').innerText =
JSON.stringify(googleUser, undefined, 2);
document.getElementById('signed-in-cell').innerText =
auth2.isSignedIn.get();
updateGoogleUser();
}
}
Если не указано иное, контент на этой странице предоставляется по лицензии Creative Commons "С указанием авторства 4.0", а примеры кода – по лицензии Apache 2.0. Подробнее об этом написано в правилах сайта. Java – это зарегистрированный товарный знак корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2025-07-25 UTC.
[null,null,["Последнее обновление: 2025-07-25 UTC."],[[["\u003cp\u003eThe Google Sign-In library optionally uses FedCM APIs, which will become a requirement, necessitating an impact assessment to ensure continued user sign-in functionality.\u003c/p\u003e\n"],["\u003cp\u003eSupport for the Google Sign-In library is now deprecated, and users should consult the Deprecation and Sunset guide for more information.\u003c/p\u003e\n"],["\u003cp\u003eListeners can be used to monitor and respond to changes in a user's sign-in session, such as changes in the \u003ccode\u003eauth2.isSignedIn\u003c/code\u003e state or the \u003ccode\u003eauth2.currentUser\u003c/code\u003e object.\u003c/p\u003e\n"],["\u003cp\u003eThe \u003ccode\u003elisten()\u003c/code\u003e method in the 2.0 client allows developers to receive real-time updates about changes in the user's sign-in status and current user information.\u003c/p\u003e\n"]]],[],null,["# Integrating Google Sign-In using listeners\n\n| **Warning:** The Google Sign-In library optionally uses FedCM APIs, and their use will become a requirement. [Conduct an impact assessment](/identity/sign-in/web/gsi-with-fedcm) to confirm that user sign-in continues to function as expected. \n|\n| Support for the Google Sign-In library is deprecated, see the [Deprecation and Sunset](/identity/sign-in/web/deprecation-and-sunset) guide for more.\n\nListeners provide a way to automatically respond to changes in the current\nuser's Sign-In session. For example, after your startup method initializes the\nGoogle Sign-In auth2 object, you can set up listeners to respond to events\nlike `auth2.isSignedIn` state changes, or changes in `auth2.currentUser`.\n\nThe following code demonstrates using the 2.0 client method\n`listen()` to respond to changes in `auth2.isSignedIn` and `auth2.currentUser`. \n\n var auth2; // The Sign-In object.\n var googleUser; // The current user.\n\n\n /**\n * Calls startAuth after Sign in V2 finishes setting up.\n */\n var appStart = function() {\n gapi.load('auth2', initSigninV2);\n };\n\n\n /**\n * Initializes Signin v2 and sets up listeners.\n */\n var initSigninV2 = function() {\n auth2 = gapi.auth2.init({\n client_id: 'CLIENT_ID.apps.googleusercontent.com',\n scope: 'profile'\n });\n\n // Listen for sign-in state changes.\n auth2.isSignedIn.listen(signinChanged);\n\n // Listen for changes to current user.\n auth2.currentUser.listen(userChanged);\n\n // Sign in the user if they are currently signed in.\n if (auth2.isSignedIn.get() == true) {\n auth2.signIn();\n }\n\n // Start with the current live values.\n refreshValues();\n };\n\n\n /**\n * Listener method for sign-out live value.\n *\n * @param {boolean} val the updated signed out state.\n */\n var signinChanged = function (val) {\n console.log('Signin state changed to ', val);\n document.getElementById('signed-in-cell').innerText = val;\n };\n\n\n /**\n * Listener method for when the user changes.\n *\n * @param {GoogleUser} user the updated user.\n */\n var userChanged = function (user) {\n console.log('User now: ', user);\n googleUser = user;\n updateGoogleUser();\n document.getElementById('curr-user-cell').innerText =\n JSON.stringify(user, undefined, 2);\n };\n\n\n /**\n * Updates the properties in the Google User table using the current user.\n */\n var updateGoogleUser = function () {\n if (googleUser) {\n document.getElementById('user-id').innerText = googleUser.getId();\n document.getElementById('user-scopes').innerText =\n googleUser.getGrantedScopes();\n document.getElementById('auth-response').innerText =\n JSON.stringify(googleUser.getAuthResponse(), undefined, 2);\n } else {\n document.getElementById('user-id').innerText = '--';\n document.getElementById('user-scopes').innerText = '--';\n document.getElementById('auth-response').innerText = '--';\n }\n };\n\n\n /**\n * Retrieves the current user and signed in states from the GoogleAuth\n * object.\n */\n var refreshValues = function() {\n if (auth2){\n console.log('Refreshing values...');\n\n googleUser = auth2.currentUser.get();\n\n document.getElementById('curr-user-cell').innerText =\n JSON.stringify(googleUser, undefined, 2);\n document.getElementById('signed-in-cell').innerText =\n auth2.isSignedIn.get();\n\n updateGoogleUser();\n }\n }"]]