Class ScriptApp

ScriptApp

Access and manipulate script publishing and triggers. This class allows users to create scripttriggers and control publishing the script as a service.

Properties

PropertyTypeDescription
AuthModeAuthModeAn enumeration that identifies which categories of authorized services Apps Script is able toexecute through a triggered function.
AuthorizationStatusAuthorizationStatusAn enumeration denoting the authorization status of a script.
EventTypeEventTypeAn enumeration denoting the type of triggered event.
InstallationSourceInstallationSourceAn enumeration denoting how the script was installed to the user as an add-on.
TriggerSourceTriggerSourceAn enumeration denoting the source of the event that causes the trigger to fire.
WeekDayWeekdayAn enumeration representing the days of the week.

Methods

MethodReturn typeBrief description
deleteTrigger(trigger)voidRemoves the given trigger so it no longer runs.
getAuthorizationInfo(authMode)AuthorizationInfoGets an object that checks if the user has granted authorization for all the scriptrequirements.
getAuthorizationInfo(authMode, oAuthScopes)AuthorizationInfoGets an object that checks if the user has granted authorization for the requested scopes.
getIdentityToken()StringGets anOpenID Connect identity token for theeffective user, if theopenid scope has been granted.
getInstallationSource()InstallationSourceReturns an enum value that indicates how the script came to be installed as an add-on for thecurrent user (for example, whether the user installed it personally through the Chrome WebStore, or whether a domain administrator installed it for all users).
getOAuthToken()StringGets the OAuth 2.0accesstoken for the effective user.
getProjectTriggers()Trigger[]Gets all installable triggers associated with the current project and current user.
getScriptId()StringGets the script project's unique ID.
getService()ServiceGets an object used to control publishing the script as a web app.
getUserTriggers(document)Trigger[]Gets all installable triggers owned by this user in the given document, for this script oradd-on only.
getUserTriggers(form)Trigger[]Gets all installable triggers owned by this user in the given form, for this script or add-ononly.
getUserTriggers(spreadsheet)Trigger[]Gets all installable triggers owned by this user in the given spreadsheet, for this script oradd-on only.
invalidateAuth()voidInvalidates the authorization the effective user has to execute the current script.
newStateToken()StateTokenBuilderCreates a builder for a state token that can be used in a callback API (like an OAuth flow).
newTrigger(functionName)TriggerBuilderBegins the process of creating an installable trigger that, when fired, calls a given function.
requireAllScopes(authMode)voidValidates if the user has granted consent for all of the scopes requested by the script.
requireScopes(authMode, oAuthScopes)voidValidates if the user has granted consent for the requested scopes.

Deprecated methods

MethodReturn typeBrief description
getProjectKey()StringGets the project key of the current script.
getScriptTriggers()Trigger[]Gets all installable triggers associated with the current project and current user.

Detailed documentation

deleteTrigger(trigger)

Removes the given trigger so it no longer runs.

// Deletes all triggers in the current project.consttriggers=ScriptApp.getProjectTriggers();for(leti=0;i <triggers.length;i++){ScriptApp.deleteTrigger(triggers[i]);}

Parameters

NameTypeDescription
triggerTriggerThe trigger to delete.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/script.scriptapp

getAuthorizationInfo(authMode)

Gets an object that checks if the user has granted authorization for all the scriptrequirements. The object also provides an authorization URL for users to grant thosepermissions, in case any of the script requirements are not authorized.

Some script executions can start without a user's consent for all required scopes used bythe script. The information in this object lets you control access to sections of code thatrequire certain scopes and request authorization of those scopes for subsequent executions.

constauthInfo=ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL);conststatus=authInfo.getAuthorizationStatus();consturl=authInfo.getAuthorizationUrl();

Parameters

NameTypeDescription
authModeAuthModeThe authorization mode for which authorization information is requested; in almost all cases, the value forauthMode should beScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL), since no other authorization mode requires that users grant authorization.

Return

AuthorizationInfo — An object that can provide information about the user's authorization status.


getAuthorizationInfo(authMode, oAuthScopes)

Gets an object that checks if the user has granted authorization for the requested scopes. Theobject also provides an authorization URL for users to grant those permissions, in case any ofthe requested scopes are not authorized.

Some script executions can start without a user's consent for all required scopes used bythe script. The information in this object lets you control access to sections of code thatrequire certain scopes and request authorization of those scopes for subsequent executions.Scopes that are invalid or notrequired bythe script lead to an error.

constauthInfo=ScriptApp.getAuthorizationInfo(ScriptApp.AuthMode.FULL,['https://www.googleapis.com/auth/documents','https://www.googleapis.com/auth/presentations',]);conststatus=authInfo.getAuthorizationStatus();consturl=authInfo.getAuthorizationUrl();

Parameters

NameTypeDescription
authModeAuthModeThe authorization mode for which authorization information is requested; in almost all cases, the value forauthMode should beScriptApp.AuthMode.FULL, since no other authorization mode requires that users grant authorization.
oAuthScopesString[]The OAuth scopes for which authorization information is requested.

Return

AuthorizationInfo — An object that provides information about the user's authorization status and an authorization URL in case some consents are missing.


getIdentityToken()

Gets anOpenID Connect identity token for theeffective user, if theopenid scope has been granted. This scope is not includedby default, and you must add it as anexplicit scope in the manifestfile to request it. Include the scopeshttps://www.googleapis.com/auth/userinfo.email orhttps://www.googleapis.com/auth/userinfo.profile to return additionaluser information in the token.

The returned ID token is an encodedJSON Web Token (JWT), andit must be decoded to extract information from it. The following examples shows how to decodethe token and extract the effective user's Google profile ID.

constidToken=ScriptApp.getIdentityToken();constbody=idToken.split('.')[1];constdecoded=Utilities.newBlob(Utilities.base64Decode(body),).getDataAsString();constpayload=JSON.parse(decoded);Logger.log(`Profile ID:${payload.sub}`);
See theOpenID Connectdocumentation for the full list of fields (claims) returned.

Return

String — The identity token if available; otherwisenull.


getInstallationSource()

Returns an enum value that indicates how the script came to be installed as an add-on for thecurrent user (for example, whether the user installed it personally through the Chrome WebStore, or whether a domain administrator installed it for all users).

Return

InstallationSource — The source of installation.


getOAuthToken()

Gets the OAuth 2.0accesstoken for the effective user. If the script's OAuth scopes are sufficient to authorizeanother Google API that normally requires its own OAuth flow (likeGoogle Picker), scripts can bypass thesecond authorization prompt by passing this token instead. The token expires after a time (afew minutes at minimum); scripts should handle authorization failures and call this method toobtain a fresh token when needed.

The token returned by this method only includes scopes that the script currently needs.Scopes that were previously authorized but are no longer used by the script are not included inthe returned token. If additional OAuth scopes are needed beyond what the script itselfrequires, they can bespecified in the script'smanifest file.

Return

String — A string representation of the OAuth 2.0 token.


getProjectTriggers()

Gets all installable triggers associated with the current project and current user.

Logger.log(`Current project has${ScriptApp.getProjectTriggers().length} triggers.`,);

Return

Trigger[] — An array of the current user's triggers associated with this project.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/script.scriptapp

getScriptId()

Gets the script project's unique ID. This is the preferred method to get the unique identifierfor the script project as opposed togetProjectKey(). This ID can be used in all placeswhere project key was previously provided.

Return

String — The script project's ID.


getService()

Gets an object used to control publishing the script as a web app.

// Get the URL of the published web app.consturl=ScriptApp.getService().getUrl();

Return

Service — An object used to observe and control publishing the script as a web app.


getUserTriggers(document)

Gets all installable triggers owned by this user in the given document, for this script oradd-on only. This method cannot be used to see the triggers attached to other scripts.

constdoc=DocumentApp.getActiveDocument();consttriggers=ScriptApp.getUserTriggers(doc);// Log the handler function for the first trigger in the array.Logger.log(triggers[0].getHandlerFunction());

Parameters

NameTypeDescription
documentDocumentA Google Docs file that may contain installable triggers.

Return

Trigger[] — An array of triggers owned by this user in the given document.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/script.scriptapp

getUserTriggers(form)

Gets all installable triggers owned by this user in the given form, for this script or add-ononly. This method cannot be used to see the triggers attached to other scripts.

constform=FormApp.getActiveForm();consttriggers=ScriptApp.getUserTriggers(form);// Log the trigger source for the first trigger in the array.Logger.log(triggers[0].getTriggerSource());

Parameters

NameTypeDescription
formFormA Google Forms file that may contain installable triggers.

Return

Trigger[] — An array of triggers owned by this user in the given form.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/script.scriptapp

getUserTriggers(spreadsheet)

Gets all installable triggers owned by this user in the given spreadsheet, for this script oradd-on only. This method cannot be used to see the triggers attached to other scripts.

constss=SpreadsheetApp.getActiveSpreadsheet();consttriggers=ScriptApp.getUserTriggers(ss);// Log the event type for the first trigger in the array.Logger.log(triggers[0].getEventType());

Parameters

NameTypeDescription
spreadsheetSpreadsheetA Google Sheets file that may contain installable triggers.

Return

Trigger[] — An array of triggers owned by this user in the given spreadsheet.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/script.scriptapp

invalidateAuth()

Invalidates the authorization the effective user has to execute the current script. Used toinvalidate any permissions for the current script. This is especially useful for functionstagged as one-shot authorization. Since one-shot authorization functions can only be called thefirst run after the script has acquired authorization, if you wish to perform an actionafterwards, you must revoke any authorization the script had, so the user can see theauthorization dialog again.

ScriptApp.invalidateAuth();

Throws

Error — when invalidation fails


newStateToken()

Creates a builder for a state token that can be used in a callback API (like an OAuth flow).

// Generate a callback URL, given the name of a callback function. The script// does not need to be published as a web app; the /usercallback URL suffix// replaces /edit in any script's URL.functiongetCallbackURL(callbackFunction){// IMPORTANT: Replace string below with the URL from your script, minus the// /edit at the end.constscriptUrl='https://script.google.com/macros/d/1234567890abcdefghijklmonpqrstuvwxyz';consturlSuffix='/usercallback?state=';conststateToken=ScriptApp.newStateToken().withMethod(callbackFunction).withTimeout(120).createToken();returnscriptUrl+urlSuffix+stateToken;}

In most OAuth2 flows, thestate token is passed to the authorization endpointdirectly (not as part of the callback URL), and the authorization endpoint then passes it aspart of the callback URL.

For example:

  • The script redirects the user to OAuth2 authorize URL:https://accounts.google.com/o/oauth2/auth?state=token_generated_with_this_method&callback_uri=https://script.google.com/macros/d/1234567890abcdefghijklmonpqrstuvwxyz/usercallback&other_oauth2_parameters
  • The user clicks authorize, and the OAuth2 authorization page redirects the user back tohttps://script.google.com/macros/d/1234567890abcdefghijklmonpqrstuvwxyz/usercallback?state=token_generated_with_this_method&other_params_that_include_tokens_or_grants
  • The above redirect (back tohttp://script.google.com/...), causes the browser request to/usercallback, which invokes the method specified byStateTokenBuilder.withMethod(method).

Return

StateTokenBuilder — An object used to continue the state-token-building process.


newTrigger(functionName)

Begins the process of creating an installable trigger that, when fired, calls a given function.

// Creates an edit trigger for a spreadsheet identified by ID.ScriptApp.newTrigger('myFunction').forSpreadsheet('1234567890abcdefghijklmnopqrstuvwxyz_a1b2c3').onEdit().create();

Before creating a trigger, verify that the associated function has all the necessaryOAuth permissions.

Parameters

NameTypeDescription
functionNameStringThe function to call when the trigger fires. You can use functions from included libraries, such asLibrary.libFunction1.

Return

TriggerBuilder — An object used to continue the trigger-building process.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/script.scriptapp

requireAllScopes(authMode)

Validates if the user has granted consent for all of the scopes requested by the script. Usethis method if an execution flow relies on all of the scopes that a script requests. If anyconsents are missing, then this method ends the current execution and renders an authorizationprompt to request the missing consents.

This method only works when users run the script from a surface that supports granularconsent, for example, from within the Apps Script IDE. When the script is run with missingconsents from an unsupported surface, such as a Google Workspace add-on, the script renders anauthorization prompt at the start of the execution to request all the scopes.

ScriptApp.requireAllScopes(ScriptApp.AuthMode.FULL);

Parameters

NameTypeDescription
authModeAuthModeThe authorization mode for which script scopes needs to be evaluated, in almost all cases, the value forauthMode should beScriptApp.AuthMode.FULL, since no other authorization mode requires that users grant authorization.

requireScopes(authMode, oAuthScopes)

Validates if the user has granted consent for the requested scopes. Use this method if anexecution flow relies on one or more services. If any of the specified consents are missing,then this method ends the current execution and renders an authorization prompt to request themissing consents. Scopes that are invalid or notrequired bythe script lead to an error.

This method only works when users run the script from a surface that supports granularconsent, for example, from within the Apps Script IDE. When the script is run with missingconsents from an unsupported surface, such as a Google Workspace add-on, the script renders anauthorization prompt at the start of the execution to request all the scopes.

ScriptApp.requireScopes(ScriptApp.AuthMode.FULL,['https://www.googleapis.com/auth/documents','https://www.googleapis.com/auth/presentations',]);

Parameters

NameTypeDescription
authModeAuthModeThe authorization mode for which requested scopes needs to be evaluated, in almost all cases, the value forauthMode should beScriptApp.AuthMode.FULL, since no other authorization mode requires that users grant authorization.
oAuthScopesString[]The OAuth scopes that are required to complete the given execution flow.

Deprecated methods

getProjectKey()

Deprecated. usegetScriptId() instead.

Gets the project key of the current script. The project key is a unique identifier for scriptsand used to compose the callback URL used in conjunction withnewStateToken().

When called in alibrary, this returns theproject key of the outer-most script being executed.

Return

String — The project key of the current script.


getScriptTriggers()

Deprecated. This function is deprecated and should not be used in new scripts.

Gets all installable triggers associated with the current project and current user.

Logger.log(`Current script has${ScriptApp.getScriptTriggers().length} triggers.`,);

Return

Trigger[] — An array of the current user's triggers associated with this project.

Authorization

Scripts that use this method require authorization with one or more of the followingscopes:

  • https://www.googleapis.com/auth/script.scriptapp

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-04-09 UTC.