Class Session
Organiza tus páginas con colecciones
Guarda y categoriza el contenido según tus preferencias.
Sesión
La clase Session proporciona acceso a la información de la sesión, como la dirección de correo electrónico del usuario (en algunas circunstancias) y la configuración de idioma.
Métodos
Método | Tipo de datos que se muestra | Descripción breve |
getActiveUser() | User | Obtiene información sobre el usuario actual. |
getActiveUserLocale() | String | Obtiene la configuración de idioma del usuario actual como una cadena; por ejemplo, en para inglés. |
getEffectiveUser() | User | Obtiene información sobre el usuario bajo cuya autoridad se ejecuta la secuencia de comandos. |
getScriptTimeZone() | String | Obtiene la zona horaria de la secuencia de comandos. |
getTemporaryActiveUserKey() | String | Obtiene una clave temporal única para el usuario activo, pero no revela su identidad. |
Métodos obsoletos
Método | Tipo de datos que se muestra | Descripción breve |
getTimeZone()
| String | Obtiene la zona horaria de la secuencia de comandos. |
getUser()
| User | Obtiene información sobre el usuario actual. |
Documentación detallada
getActiveUser()
Obtiene información sobre el usuario actual. Si las políticas de seguridad no permiten el acceso a la identidad del usuario, User.getEmail()
muestra una cadena vacía. Las circunstancias en las que la dirección de correo electrónico está disponible varían: por ejemplo, la dirección de correo electrónico del usuario no está disponible en ningún contexto que permita que se ejecute una secuencia de comandos sin la autorización de ese usuario, como un activador onOpen(e)
o onEdit(e)
simple, una función personalizada en Hojas de cálculo de Google o una app web implementada para "ejecutarse como yo" (es decir, autorizada por el desarrollador en lugar del usuario).
Sin embargo, estas restricciones generalmente no se aplican si el desarrollador ejecuta la secuencia de comandos por su cuenta o pertenece al mismo dominio de Google Workspace que el usuario.
// Log the email address of the person running the script.
const email = Session.getActiveUser().getEmail();
Logger.log(email);
Volver
User
: El usuario actual
Autorización
Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes ámbitos:
-
https://www.googleapis.com/auth/userinfo.email
getActiveUserLocale()
Obtiene la configuración de idioma del usuario actual como una cadena; por ejemplo, en
para inglés.
// Log the language setting of the person running the script.
Logger.log(Session.getActiveUserLocale());
Volver
String
: Es una cadena que representa la configuración de idioma del usuario.
getEffectiveUser()
Obtiene información sobre el usuario bajo cuya autoridad se ejecuta la secuencia de comandos. Si la secuencia de comandos es una app web configurada para "ejecutarse como yo" (el desarrollador), se muestra la cuenta de usuario del desarrollador. Si la secuencia de comandos se ejecuta con un activador instalable, se muestra la cuenta del usuario que creó el activador. En la mayoría de los demás casos, muestra la misma cuenta que getActiveUser()
.
// Log the email address of the user under whose authority the script is
// running.
const email = Session.getEffectiveUser().getEmail();
Logger.log(email);
Volver
User
: Es el usuario bajo cuya autoridad se ejecuta la secuencia de comandos.
Autorización
Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes ámbitos:
-
https://www.googleapis.com/auth/userinfo.email
getScriptTimeZone()
Obtiene la zona horaria de la secuencia de comandos. Las secuencias de comandos nuevas usan de forma predeterminada la zona horaria del propietario, pero se puede cambiar haciendo clic en File > Project properties en el editor de secuencia de comandos. Ten en cuenta que las hojas de cálculo tienen una zona horaria independiente, que se puede cambiar haciendo clic en
Archivo > Configuración de la hoja de cálculo en Hojas de cálculo de Google. Las zonas horarias de las hojas de cálculo que difieren de la zona horaria de la secuencia de comandos son una fuente frecuente de errores de secuencias de comandos.
// Log the time zone of the script.
const timeZone = Session.getScriptTimeZone();
Logger.log(timeZone);
Volver
String
: Es la zona horaria de la secuencia de comandos.
getTemporaryActiveUserKey()
Obtiene una clave temporal única para el usuario activo, pero no revela su identidad.
La clave temporal rota cada 30 días y es única para la secuencia de comandos.
// Log the temporary key of the person running the script.
Logger.log(Session.getTemporaryActiveUserKey());
Volver
String
: Es la clave de usuario activo temporal.
Métodos obsoletos
getTimeZone()
Obsoleto. Esta función dejó de estar disponible y no se debe usar en secuencias de comandos nuevas.
Obtiene la zona horaria de la secuencia de comandos. Las secuencias de comandos nuevas usan de forma predeterminada la zona horaria del propietario, pero se puede cambiar haciendo clic en File > Project properties en el editor de secuencia de comandos. Ten en cuenta que las hojas de cálculo tienen una zona horaria independiente, que se puede cambiar haciendo clic en
Archivo > Configuración de la hoja de cálculo en Hojas de cálculo de Google. Las zonas horarias de las hojas de cálculo que difieren de la zona horaria de la secuencia de comandos son una fuente frecuente de errores de secuencias de comandos.
// Log the time zone of the script.
const timeZone = Session.getTimeZone();
Logger.log(timeZone);
Volver
String
: Es la zona horaria de la secuencia de comandos.
getUser()
Obsoleto. Esta función dejó de estar disponible y no se debe usar en secuencias de comandos nuevas.
Obtiene información sobre el usuario actual.
Volver
User
: El usuario que accedió
Autorización
Las secuencias de comandos que usan este método requieren autorización con uno o más de los siguientes ámbitos:
-
https://www.googleapis.com/auth/userinfo.email
Salvo que se indique lo contrario, el contenido de esta página está sujeto a la licencia Atribución 4.0 de Creative Commons, y los ejemplos de código están sujetos a la licencia Apache 2.0. Para obtener más información, consulta las políticas del sitio de Google Developers. Java es una marca registrada de Oracle o sus afiliados.
Última actualización: 2025-07-26 (UTC)
[null,null,["Última actualización: 2025-07-26 (UTC)"],[[["\u003cp\u003eThe \u003ccode\u003eSession\u003c/code\u003e class in Apps Script allows you to access information about the current user and the script's environment, such as the user's locale and the script's time zone.\u003c/p\u003e\n"],["\u003cp\u003eYou can retrieve information about the active user, effective user, script time zone, and a temporary active user key using methods like \u003ccode\u003egetActiveUser()\u003c/code\u003e, \u003ccode\u003egetEffectiveUser()\u003c/code\u003e, \u003ccode\u003egetScriptTimeZone()\u003c/code\u003e, and \u003ccode\u003egetTemporaryActiveUserKey()\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eSome methods like \u003ccode\u003egetTimeZone()\u003c/code\u003e and \u003ccode\u003egetUser()\u003c/code\u003e are deprecated and should be replaced with their updated counterparts such as \u003ccode\u003egetScriptTimeZone()\u003c/code\u003e and \u003ccode\u003egetActiveUser()\u003c/code\u003e.\u003c/p\u003e\n"],["\u003cp\u003eWhile the user's email address can be accessed in certain circumstances using \u003ccode\u003egetActiveUser().getEmail()\u003c/code\u003e or \u003ccode\u003egetEffectiveUser().getEmail()\u003c/code\u003e, it may not be available if security policies restrict access or in contexts without explicit user authorization.\u003c/p\u003e\n"],["\u003cp\u003eAccessing user information may require specific authorization scopes, like \u003ccode\u003ehttps://www.googleapis.com/auth/userinfo.email\u003c/code\u003e, to be granted to the script.\u003c/p\u003e\n"]]],[],null,["# Class Session\n\nSession\n\nThe Session class provides access to session information, such as the user's email address (in\nsome circumstances) and language setting. \n\n### Methods\n\n| Method | Return type | Brief description |\n|-------------------------------------------------------------|------------------------------------------|-----------------------------------------------------------------------------------------------|\n| [getActiveUser()](#getActiveUser()) | [User](/apps-script/reference/base/user) | Gets information about the current user. |\n| [getActiveUserLocale()](#getActiveUserLocale()) | `String` | Gets the language setting of the current user as a string---for example, `en` for English. |\n| [getEffectiveUser()](#getEffectiveUser()) | [User](/apps-script/reference/base/user) | Gets information about the user under whose authority the script is running. |\n| [getScriptTimeZone()](#getScriptTimeZone()) | `String` | Gets the time zone of the script. |\n| [getTemporaryActiveUserKey()](#getTemporaryActiveUserKey()) | `String` | Gets a temporary key that is unique to the active user but does not reveal the user identity. |\n\n### Deprecated methods\n\n| Method | Return type | Brief description |\n|---------------------------------|------------------------------------------|------------------------------------------|\n| [getTimeZone()](#getTimeZone()) | `String` | Gets the time zone of the script. |\n| [getUser()](#getUser()) | [User](/apps-script/reference/base/user) | Gets information about the current user. |\n\nDetailed documentation\n----------------------\n\n### `get``Active``User()`\n\nGets information about the current user. If security policies do not allow access to the user's\nidentity, [User.getEmail()](/apps-script/reference/base/user#getEmail()) returns a blank string. The circumstances in which the\nemail address is available vary: for example, the user's email address is not available in any\ncontext that allows a script to run without that user's authorization, like a simple `on``Open(e)` or `on``Edit(e)` trigger, a custom function in Google Sheets, or a web app\ndeployed to \"execute as me\" (that is, authorized by the developer instead of the user).\nHowever, these restrictions generally do not apply if the developer runs the script themselves\nor belongs to the same Google Workspace domain as the user.\n\n```javascript\n// Log the email address of the person running the script.\nconst email = Session.getActiveUser().getEmail();\nLogger.log(email);\n```\n\n#### Return\n\n\n[User](/apps-script/reference/base/user) --- the current user\n\n#### Authorization\n\nScripts that use this method require authorization with one or more of the following [scopes](/apps-script/concepts/scopes#setting_explicit_scopes):\n\n- `https://www.googleapis.com/auth/userinfo.email`\n\n*** ** * ** ***\n\n### `get``Active``User``Locale()`\n\nGets the language setting of the current user as a string---for example, `en` for English.\n\n```javascript\n// Log the language setting of the person running the script.\nLogger.log(Session.getActiveUserLocale());\n```\n\n#### Return\n\n\n`String` --- a string that represents the user's language setting\n\n*** ** * ** ***\n\n### `get``Effective``User()`\n\nGets information about the user under whose authority the script is running. If the script is a\nweb app set to \"execute as me\" (the developer), this returns the developer's user account. If\nthe script is running under an [installable\ntrigger](/apps-script/understanding_triggers), this returns the account of the user who created the trigger. In most other\nscenarios, this returns the same account as [getActiveUser()](#getActiveUser()).\n\n```javascript\n// Log the email address of the user under whose authority the script is\n// running.\nconst email = Session.getEffectiveUser().getEmail();\nLogger.log(email);\n```\n\n#### Return\n\n\n[User](/apps-script/reference/base/user) --- the user under whose authority the script is running\n\n#### Authorization\n\nScripts that use this method require authorization with one or more of the following [scopes](/apps-script/concepts/scopes#setting_explicit_scopes):\n\n- `https://www.googleapis.com/auth/userinfo.email`\n\n*** ** * ** ***\n\n### `get``Script``Time``Zone()`\n\nGets the time zone of the script. New scripts default to the owner's time zone, but the\nscript's time zone can be changed by clicking **File \\\u003e Project properties** in the script\neditor. Note that spreadsheets have a separate time zone, which can be changed by clicking\n**File \\\u003e Spreadsheet settings** in Google Sheets. Spreadsheet time zones that differ from\nthe script time zone are a frequent source of scripting bugs.\n\n```javascript\n// Log the time zone of the script.\nconst timeZone = Session.getScriptTimeZone();\nLogger.log(timeZone);\n```\n\n#### Return\n\n\n`String` --- the time zone of the script\n\n*** ** * ** ***\n\n### `get``Temporary``Active``User``Key()`\n\nGets a temporary key that is unique to the active user but does not reveal the user identity.\nThe temporary key rotates every 30 days and is unique to the script.\n\n```javascript\n// Log the temporary key of the person running the script.\nLogger.log(Session.getTemporaryActiveUserKey());\n```\n\n#### Return\n\n\n`String` --- the temporary active user key\n\nDeprecated methods\n------------------\n\n### `get``Time``Zone()`\n\n\n**Deprecated.** This function is deprecated and should not be used in new scripts.\n\nGets the time zone of the script. New scripts default to the owner's time zone, but the\nscript's time zone can be changed by clicking **File \\\u003e Project properties** in the script\neditor. Note that spreadsheets have a separate time zone, which can be changed by clicking\n**File \\\u003e Spreadsheet settings** in Google Sheets. Spreadsheet time zones that differ from\nthe script time zone are a frequent source of scripting bugs.\n\n```javascript\n// Log the time zone of the script.\nconst timeZone = Session.getTimeZone();\nLogger.log(timeZone);\n```\n\n#### Return\n\n\n`String` --- the time zone of the script\n\n*** ** * ** ***\n\n### `get``User()`\n\n\n**Deprecated.** This function is deprecated and should not be used in new scripts.\n\nGets information about the current user.\n\n#### Return\n\n\n[User](/apps-script/reference/base/user) --- the currently signed in user\n\n#### Authorization\n\nScripts that use this method require authorization with one or more of the following [scopes](/apps-script/concepts/scopes#setting_explicit_scopes):\n\n- `https://www.googleapis.com/auth/userinfo.email`"]]