Praveen M
Praveen M

Reputation: 11

What is the difference between onOpen(e) and onOpen()?

I have gone through many documentation from Google Apps Script and I have seen onOpen(e) and onOpen() are used in many examples. Both of them look familiar to me and I'm new to Google addon, which one is best to use for regular practice?

Upvotes: 0

Views: 1470

Answers (1)

Rafa Guillermo
Rafa Guillermo

Reputation: 15377

Answer:

onOpen(e) with an event object brings contextual information that can be used in the function. If none of this information is needed, then you can omit the event object by using onOpen(). Both will run when the file to which the script is bound is opened, but you can only have one function with this name in your script.

The Event Object:

Depending on the type of file that the script is bound to, the event object will have different parameters that can be accessed, as can be seen in the event object documentation

Example:

function onOpen(e) {
  e.source.getSheets()[0].getRange("A1").setValue("I ran!")
}

In this example, as a part of the event object passed to the script, the source parameter is a Spreadsheet object which you can use to manpulate the Spreadsheet to which the script is bound. Without the event object, you would have to directly call the SpreadsheetApp method to obtain the data:

function onOpen() {
  const ss = SpreadsheetApp.getActiveSpreadsheet()
  ss.getSheets()[0].getRange("A1").setValue("I ran!")
}

This is a simple example showing the source parameter, but there are others such as e.authMode which can be used to determine the installation state of an add-on, and e.user which displays the email address of the user that ran the script.

You can read more information about the event object and how to use them for each trigger and service at the above link.

References:

Upvotes: 3

Related Questions