### Install Rust
Source: https://github.com/googleworkspace/apps-script-samples/blob/main/wasm/python/README.md
Install Rust using the official installation guide. This is a prerequisite for the project.
```bash
https://www.rust-lang.org/tools/install
```
--------------------------------
### Install Node.js
Source: https://github.com/googleworkspace/apps-script-samples/blob/main/wasm/python/README.md
Install Node.js from the official website. This is a prerequisite for the project.
```bash
https://nodejs.org/en/download
```
--------------------------------
### Install Binaryen
Source: https://github.com/googleworkspace/apps-script-samples/blob/main/wasm/python/README.md
Install Binaryen, which includes wasm-opt. This is a prerequisite for the project.
```bash
https://github.com/WebAssembly/binaryen
```
--------------------------------
### Install Node.js Dependencies
Source: https://github.com/googleworkspace/apps-script-samples/blob/main/wasm/hello-world/README.md
Run this command to install project dependencies using npm. Ensure Node.js is installed.
```bash
npm i
```
--------------------------------
### Build Project with npm
Source: https://github.com/googleworkspace/apps-script-samples/blob/main/wasm/hello-world/README.md
Execute this command to build the project after installing dependencies. This command is part of the development workflow for integrating external languages into Apps Script.
```bash
npm run build
```
--------------------------------
### Initiate Authorization Flow
Source: https://github.com/googleworkspace/apps-script-samples/blob/main/templates/sheets-import/JavaScript.html
Starts the OAuth authorization process. Opens a new window with the authorization URL upon success.
```javascript
function onAuthorizeClick() {
google.script.run
.withSuccessHandler(openUrlWindow)
.withFailureHandler(reportError)
.getAuthorizationUrl();
}
```
--------------------------------
### Lint and Format Code with Biome
Source: https://github.com/googleworkspace/apps-script-samples/blob/main/GEMINI.md
Use Biome to lint and format your Apps Script code. Ensure Biome is installed in your project.
```bash
pnpm lint
pnpm format
```
--------------------------------
### Lint Repository with pnpm
Source: https://github.com/googleworkspace/apps-script-samples/blob/main/README.md
Run ESLint to check and automatically fix simple errors in the repository. Ensure pnpm is installed.
```shell
pnpm lint
```
--------------------------------
### Get Initial Calendar Settings
Source: https://github.com/googleworkspace/apps-script-samples/blob/main/solutions/automations/calendar-timesheet/Page.html
This function initiates the retrieval of initial calendar settings from the server-side Apps Script using 'google.script.run'. It specifies failure and success handlers for the asynchronous operation.
```javascript
google.script.run
.withFailureHandler(onFailure)
.withSuccessHandler(onSuccessGetSettings)
.getSettings();
```
--------------------------------
### Concise Function Expressions with Arrow Functions
Source: https://github.com/googleworkspace/apps-script-samples/blob/main/GEMINI.md
Utilize arrow functions for concise function expressions, particularly beneficial for callbacks. This example demonstrates mapping an array to its squares.
```javascript
const numbers = [1, 2, 3];
const squares = numbers.map(x => x * x); // [1, 4, 9]
```
--------------------------------
### Default Parameter Values in Functions
Source: https://github.com/googleworkspace/apps-script-samples/blob/main/GEMINI.md
Specify default values for function parameters to handle cases where arguments are not provided. This example shows a default name for a greeting function.
```javascript
function greet(name = "Guest") {
console.log(`Hello, ${name}!`);
}
greet(); // "Hello, Guest!"
```
--------------------------------
### Evaluate HTML Template for Web App
Source: https://context7.com/googleworkspace/apps-script-samples/llms.txt
Serves HTML content for HTTP GET requests to a web app. It can dynamically set a 'folderId' variable in the template based on URL parameters.
```javascript
/**
* Serves HTML for HTTP GET requests to the web app.
* @param {Object} e Event parameter with URL parameters.
* @return {HtmlOutput} The web app's HTML.
*/
function doGet(e) {
const template = HtmlService.createTemplateFromFile("Index");
if (e.parameter.folderId) {
template.folderId = e.parameter.folderId;
} else {
template.folderId = "root";
}
return template.evaluate().setTitle("Drive File Browser");
}
```
--------------------------------
### Initialize Dialog and Get Document Title
Source: https://github.com/googleworkspace/apps-script-samples/blob/main/templates/docs-addon/DialogJavaScript.html
This snippet initializes dialog elements and fetches the current document title when the dialog loads. It uses `google.script.run` to call a server-side function and handles success or failure responses.
```javascript
$(function() {
// Assign handler functions to dialog elements here, if needed.
$('#title-form').submit(onTitleSave);
// Call the server here to retrieve any information needed to build
// the dialog, if necessary.
google.script.run
.withSuccessHandler(function(title) {
// Respond to success conditions here.
$('#dialog-title').val(title);
showStatus('Ready.');
})
.withFailureHandler(function(msg) {
// Respond to failure conditions here.
showStatus('Error retrieving title: ' + msg, 'error');
})
.getDocTitle();
});
```
--------------------------------
### Initialize UI and Event Handlers
Source: https://github.com/googleworkspace/apps-script-samples/blob/main/templates/sheets-import/JavaScript.html
Sets up the initial sidebar view and binds click/change/keyup event handlers for various UI elements. It also listens for an 'oauthComplete' intercom signal to toggle the UI view.
```javascript
$(function() { // Pull in template parameters and set the initial sidebar view. toggleUiView(isAuthorized); // Add UI interaction handlers. $('#authorize').bind('click', onAuthorizeClick); $('#signout').bind('click', onSignoutClick); $('#column-options').click(addSelectedColumnOption); $('#columns-selected').click(removeSelectedColumnOption); $('#report-name').keyup(verifyAndEnableSave); $('#report-select').change(onReportSelect); $('#save-report').click(onSaveClick); $('#run-report').click(onRunClick); $('#delete-report').click(onDeleteClick); // Listen for auth complete intercom signal & toggle UI when received. var intercom = Intercom.getInstance(); intercom.on('oauthComplete', function(data) { if (data.user === user) { toggleUiView(data.isAuthorized); } }); // Get existing reports & load them into the report select box. refreshReportAndColumnLists(); });
```
--------------------------------
### List Upcoming Calendar Events using Advanced Service
Source: https://context7.com/googleworkspace/apps-script-samples/llms.txt
Lists the 10 upcoming events from the user's primary Google Calendar using the Calendar Advanced Service. It filters events by start time and orders them by start time.
```javascript
/**
* Lists 10 upcoming events in the user's primary calendar.
* @see https://developers.google.com/calendar/api/v3/reference/events/list
*/
function listUpcomingEvents() {
const calendarId = "primary";
const optionalArgs = {
timeMin: new Date().toISOString(),
showDeleted: false,
singleEvents: true,
maxResults: 10,
orderBy: "startTime",
};
try {
const response = Calendar.Events.list(calendarId, optionalArgs);
const events = response.items;
if (events.length === 0) {
console.log("No upcoming events found");
return;
}
for (const event of events) {
let when = event.start.dateTime;
if (!when) {
when = event.start.date; // All-day events
}
console.log("%s (%s)", event.summary, when);
}
} catch (err) {
console.log("Failed with error %s", err.message);
}
}
```
--------------------------------
### Get Google Form by ID using Apps Script
Source: https://github.com/googleworkspace/apps-script-samples/blob/main/forms-api/demos/AppsScriptFormsAPIWebApp/Main.html
Retrieves a Google Form by its ID. This function calls the server-side `get` function via `google.script.run` and displays the raw API response. Ensure the form ID is correctly set in the `globalFormId` input.
```javascript
function get() {
const status = document.getElementById('status');
status.innerHTML = "Get form by id...";
const formId = document.getElementById('globalFormId');
google.script.run
.withFailureHandler(function(error) {
console.log('Error calling server function get: ' + error);
})
.withSuccessHandler(function(result) {
console.log('Raw response from Forms API: ' + result);
status.innerHTML = '
' + result + '
';
}).get(formId.value);
```
--------------------------------
### Initialize UI and Load Preferences on Document Load
Source: https://github.com/googleworkspace/apps-script-samples/blob/main/ai/autosummarize/sidebar.html
Assigns click handlers to buttons and attempts to load user preferences when the document is loaded. This is typically used for setting up the initial state of a web app or sidebar.
```javascript
$(function() {
$('#run').click(runScript);
});
```
--------------------------------
### Fetch and Format Data for Data Studio Connector
Source: https://context7.com/googleworkspace/apps-script-samples/llms.txt
Retrieves data from an external API based on user configuration and date range, then formats it for Data Studio. Requires `UrlFetchApp` and `JSON.parse`.
```javascript
/**
* Gets data from an external API and returns it in the required format.
* @param {object} request The data request object.
* @return {object} The data response.
*/
function getData(request) {
const requestedFieldIds = request.fields.map((field) => field.name);
const requestedFields = getFields().forIds(requestedFieldIds);
// Fetch data from npm API
const url = [
"https://api.npmjs.org/downloads/range/",
request.dateRange.startDate,
":",
request.dateRange.endDate,
"/",
request.configParams.package,
].join("");
const response = UrlFetchApp.fetch(url);
const parsedResponse = JSON.parse(response).downloads;
// Transform data to rows
const rows = parsedResponse.map((dailyDownload) => {
const row = [];
for (const field of requestedFields.asArray()) {
switch (field.getId()) {
case "day":
row.push(dailyDownload.day.replace(/-/g, ""));
break;
case "downloads":
row.push(dailyDownload.downloads);
break;
case "packageName":
row.push(request.configParams.package);
break;
}
}
return { values: row };
});
return {
schema: requestedFields.build(),
rows: rows,
};
}
```
--------------------------------
### Build Data Studio Community Connector Config
Source: https://context7.com/googleworkspace/apps-script-samples/llms.txt
Configures user settings for a Data Studio Community Connector. Use this to define input fields and instructions for users.
```javascript
/**
* Builds the Community Connector config for user configuration.
* @return {Config} The Community Connector config.
*/
function getConfig() {
const cc = DataStudioApp.createCommunityConnector();
const config = cc.getConfig();
config
.newInfo()
.setId("instructions")
.setText("Enter npm package names to fetch their download count.");
config
.newTextInput()
.setId("package")
.setName("Enter a single package name.")
.setHelpText("for example, googleapis or lighthouse")
.setPlaceholder("googleapis")
.setAllowOverride(true);
config.setDateRangeRequired(true);
return config.build();
}
```
--------------------------------
### Get Google Docs Document Title
Source: https://context7.com/googleworkspace/apps-script-samples/llms.txt
Retrieves and logs the title of a Google Document using its ID. Ensure you have the correct document ID.
```javascript
/**
* Retrieves and prints the title of a Google Doc.
* @see https://developers.google.com/docs/api/reference/rest/v1/documents/get
*/
function printDocTitle() {
const documentId = "YOUR_DOCUMENT_ID";
const doc = Docs.Documents.get(documentId, { includeTabsContent: true });
console.log(`The title of the doc is: ${doc.title}`);
}
```
--------------------------------
### Initialize Web App on Load
Source: https://github.com/googleworkspace/apps-script-samples/blob/main/templates/web-app/JavaScript.html
This snippet initializes the web app by calling a server-side function to retrieve data. It handles both successful data retrieval and failures, updating the UI accordingly.
```javascript
$(function() {
// Call the server here to retrieve any information needed to build the page.
google.script.run
.withSuccessHandler(function(contents) {
// Respond to success conditions here.
updateDisplay(contents);
})
.withFailureHandler(function(msg) {
// Respond to failure conditions here.
$('#main-heading').text(msg);
$('#main-heading').addClass("error");
$('#error-message').show();
})
.getFolderContents(folderId);
});
```
--------------------------------
### Get File Metadata from Drive
Source: https://context7.com/googleworkspace/apps-script-samples/llms.txt
Retrieves metadata for a specified file from Google Drive using its ID. Requires the Drive Advanced Service to be enabled.
```javascript
/**
* Gets file metadata for a selected file.
* @param {string} fileId The ID of the file.
* @return {Object} The file resource.
*/
function getFile(fileId) {
return Drive.Files.get(fileId, { fields: "*" });
}
```
--------------------------------
### Initialize Translation UI
Source: https://github.com/googleworkspace/apps-script-samples/blob/main/slides/translate/sidebar.html
Sets up the language selection radio buttons and attaches a click handler to the translate button. This code runs in the browser.
```javascript
$(function() { // Add an input radio button for every language. const languages = { ar: 'Arabic', zh: 'Chinese', en: 'English', fr: 'French', de: 'German', hi: 'Hindi', ja: 'Japanese', pt: 'Portuguese', es: 'Spanish' }; const languageList = Object.keys(languages).map((id)=> { return $('