Welcome to Software Development on Codidact!
Will you help us build our independent community of developers helping developers? We're small and trying to grow. We welcome questions about all aspects of software development, from design to code to QA and more. Got questions? Got answers? Got code you'd like someone to review? Please join us.
How to solve the "ReferenceError: service is not defined"?
Temporary notice: this is part of an ongoing project of transferring and splitting my canonical from Stack Overflow on common errors in Google Apps Script. As soon as the Q&As are finalized, it will be removed.
Attempting to call a method of an advanced service can sometimes result in a ReferenceError that the service is not defined despite Google's documentation specifying it as a global object. The exact error message is always structured as follows:
ReferenceError: <service name> is not defined
What is the underlying reason for the error and how to solve it?
1 answer
Meaning
If the script is using any of the advanced services, they must be enabled first. If the service is not enabled, it will not be added to the global scope (as a value of a global variable), resulting in an instance of ReferenceError
being thrown (as the script is referencing a non-existent variable).
Reproducing
To get a reference error when calling a method on an advanced service, declare and run the following function in a new script or one that does not have the Advanced Drive Service enabled:
const driveServiceIsNotDefined = () => {
try {
Drive.Files.list({ q: "" })
} catch(e) {
console.log(e)
}
}
Fixing
If you are using Google's online IDE, since the overhaul of it, simply open the "Editor" tab from the left sidebar, click on the "Add a service" button under the "Services" section, and then choose the appropriate service.
Note that the modal allows you to override the identifier of the service to a name of your liking (the default name matches how Google's documentation references the service). If you change it, the script will have to reference that identifier instead of the service name.
Historical aside: in the old IDE, one needed to go to "Resources -> Advanced Google Services" menu and enable the referenced service there (the identifier could be overridden too).
If you are developing locally and using CLASP to push the source code to the project, you will have to explicitly specify the advanced services used in the manifest file. In fact, this is what is done under the hood when you enable the service in the GUI.
In the manifest, advanced services are specified under the dependencies
field in the enabledAdvancedServices
(which is a JSON array of service definitions), for example (enabling the Advanced Drive Service):
"dependencies": {
"enabledAdvancedServices": [
{
"userSymbol": "Drive", // identifier to reference
"version": "v2", // version of the service to use
"serviceId": "drive" // Google's service identifier
}
]
}
0 comment threads