Мониторинг состояния сеанса пользователя
Оптимизируйте свои подборки
Сохраняйте и классифицируйте контент в соответствии со своими настройками.
После инициализации клиента входа в Google вы можете подключить обработчики, которые проверяют различные атрибуты и методы клиента, чтобы определить состояние сеанса пользователя. Вы можете использовать информацию, возвращаемую клиентским объектом, чтобы синхронизировать взаимодействие с пользователем вашего сайта на нескольких вкладках и устройствах для вашего пользователя.
В следующем коде показано использование клиентского метода attachClickHandler
версии 2.0 для создания обратного вызова, который либо автоматически завершает вход пользователя в систему, либо предлагает пользователю выполнить повторную авторизацию в зависимости от состояния сеанса пользователя.
/**
* The Sign-In client object.
*/
var auth2;
/**
* Initializes the Sign-In client.
*/
var initClient = function() {
gapi.load('auth2', function(){
/**
* Retrieve the singleton for the GoogleAuth library and set up the
* client.
*/
auth2 = gapi.auth2.init({
client_id: 'CLIENT_ID.apps.googleusercontent.com'
});
// Attach the click handler to the sign-in button
auth2.attachClickHandler('signin-button', {}, onSuccess, onFailure);
});
};
/**
* Handle successful sign-ins.
*/
var onSuccess = function(user) {
console.log('Signed in as ' + user.getBasicProfile().getName());
};
/**
* Handle sign-in failures.
*/
var onFailure = function(error) {
console.log(error);
};
Если не указано иное, контент на этой странице предоставляется по лицензии Creative Commons "С указанием авторства 4.0", а примеры кода – по лицензии Apache 2.0. Подробнее об этом написано в правилах сайта. Java – это зарегистрированный товарный знак корпорации Oracle и ее аффилированных лиц.
Последнее обновление: 2025-07-25 UTC.
[null,null,["Последнее обновление: 2025-07-25 UTC."],[[["\u003cp\u003eThe Google Sign-In JavaScript library is deprecated and will eventually be sunset; developers should consult the Deprecation and Sunset guide for migration details and timelines.\u003c/p\u003e\n"],["\u003cp\u003eGoogle Sign-In will require the use of FedCM APIs in the future, so developers should conduct an impact assessment to ensure their sign-in functionality remains unaffected.\u003c/p\u003e\n"],["\u003cp\u003eThis page provides code demonstrating how to initialize the Google Sign-In client and attach click handlers to manage user sign-in and session state.\u003c/p\u003e\n"],["\u003cp\u003eDevelopers can utilize the \u003ccode\u003eauth2\u003c/code\u003e object to handle successful and failed sign-in attempts, accessing user information upon successful authentication.\u003c/p\u003e\n"]]],[],null,["# Monitoring the user's session state\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\nAfter the Google Sign-In client has been initialized, you can attach\nhandlers that check various attributes and methods of the client to determine\nthe user's session state. You can use information returned by the client object\nto help sync your site's user experience across multiple tabs and devices for\nyour user.\n\nThe following code demonstrates using the 2.0 client method\n`attachClickHandler` to create a callback that either silently finishes sign-in\nfor the user, or prompts the user to re-authorize based on the state of the\nuser's session. \n\n /**\n * The Sign-In client object.\n */\n var auth2;\n\n /**\n * Initializes the Sign-In client.\n */\n var initClient = function() {\n gapi.load('auth2', function(){\n /**\n * Retrieve the singleton for the GoogleAuth library and set up the\n * client.\n */\n auth2 = gapi.auth2.init({\n client_id: 'CLIENT_ID.apps.googleusercontent.com'\n });\n\n // Attach the click handler to the sign-in button\n auth2.attachClickHandler('signin-button', {}, onSuccess, onFailure);\n });\n };\n\n /**\n * Handle successful sign-ins.\n */\n var onSuccess = function(user) {\n console.log('Signed in as ' + user.getBasicProfile().getName());\n };\n\n /**\n * Handle sign-in failures.\n */\n var onFailure = function(error) {\n console.log(error);\n };"]]