Google Apps Script Example Code
Google Apps Script Example Code
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
1
4: Moving a File to a Folder
5: Sharing a File
6: Changing File Permissions
7: Deleting a File
8: Listing Files in a Folder
9: Creating a Google Docs File
10: Reading File Content
Introduction to FormApp
1: Creating a New Form
2: Adding a Multiple-Choice Question
3: Creating a Form Response
4: Adding a Section Header
5: Retrieving Form Responses
6: Adding a Date Question
7: Sending Form via Email
8: Changing Form Theme
9: Adding a Linear Scale Question
10: Deleting a Form Item
Introduction to GmailApp
1: Sending an Email
2: Searching Emails
3: Applying Labels to Emails
4: Marking Emails as Read
5: Retrieving Unread Emails
6: Sending an Email with Attachment
7: Creating a Draft Email
8: Deleting an Email Thread
9: Counting Emails from a Sender
10: Fetching Email Body Content
Introduction to MailApp
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
2
1: Sending a Basic Email
2: Sending an Email with HTML Body
3: Sending Emails to Multiple Recipients
4: Sending an Email with Cc and Bcc
5: Sending an Email with an Attachment
6: Sending an Email with Inline Images
7: Retrieving Quota Information
8: Sending a Rich Text Email
9: Setting Reply-To Address
10: Sending Email with Advanced Options
Introduction to SpreadsheetApp
1: Creating a New Spreadsheet
2: Adding Data to a Cell
3: Reading Data from a Range
4: Appending a Row of Data
5: Setting a Formula in a Cell
6: Changing Cell Background Color
7: Finding and Replacing Data
8: Adding a New Sheet
9: Protecting a Range
10: Sorting Data in a Range
Introduction to SlidesApp
1: Creating a New Presentation
2: Adding a Text Box
3: Changing Slide Background Color
4: Adding an Image
5: Duplicating a Slide
6: Adding a Slide with a Predefined Layout
7: Replacing Text in Slides
8: Creating a Hyperlink
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
3
9: Changing Text Style
10: Deleting a Slide
Introduction to ContentService
1: Serving Plain Text Content
Introduction to HtmlService
1: Creating a Simple HTML Page
2: Serving an HTML File
3: Embedding JavaScript in HTML Service
4: Using Templated HTML
5: Serving CSS with HTML
6: Communicating with Google Apps Script Functions
7: Passing Data from Client to Server
8: Incorporating Google Material Design
9: Creating a User Interface for Spreadsheet
10: Serving HTML with IFrame Sandbox Mode
Introduction to HtmlOutput
1: Creating Basic HTML Output
2: Setting the Title of HTML Output
3: Adding Inline CSS to HTML Output
4: Serving HTML Output as a Web App
5: Including JavaScript in HTML Output
6: Using Templated HTML in HTML Output
7: Serving HTML Output with Custom Fonts
8: Embedding External JavaScript and CSS
Introduction to TextOutput
1: Creating Basic Text Output
2: Setting Content Type of Text Output
3: Returning JSON Data
4: Serving Text Output as a Web App
5: Serving XML Data
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
4
6: Returning CSV Data
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
5
upload files, search for files, move them to folders, share files, change
permissions, delete files, list files in folders, create Google Docs files, and
read file content.
Section 4: Introduction to FormApp
FormApp empowers you to create and manage Google Forms
programmatically. Learn how to create new forms, add questions, manage
form responses, add section headers, retrieve responses, work with date
questions, send forms via email, change form themes, add linear scale
questions, and delete form items.
Section 5: Introduction to GmailApp
GmailApp allows you to interact with Gmail programmatically. Explore tasks
like sending emails, searching emails, applying labels, marking emails as
read, retrieving unread emails, sending emails with attachments, creating
draft emails, deleting email threads, counting emails from specific senders,
and fetching email body content.
Section 6: Introduction to MailApp
MailApp enables you to send and manage emails programmatically. Learn
how to send basic emails, craft HTML-rich emails, send emails to multiple
recipients, use Cc and Bcc, send emails with attachments and inline
images, retrieve quota information, send rich-text emails, set reply-to
addresses, and explore advanced email options.
Section 7: Introduction to SpreadsheetApp
SpreadsheetApp empowers you to work with Google Sheets
programmatically. Discover how to create new spreadsheets, add data to
cells, read data from ranges, append rows, set formulas, change cell
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
6
backgrounds, find and replace data, add new sheets, protect ranges, and
sort data in ranges.
Section 8: Introduction to SlidesApp
SlidesApp lets you create and manage Google Slides presentations
programmatically. Learn how to create new presentations, add text boxes,
change slide backgrounds, insert images, duplicate slides, use predefined
layouts, replace text in slides, create hyperlinks, change text styles, and
delete slides.
Section 9: Introduction to ContentService
ContentService is your tool for serving web content programmatically.
Explore serving plain text, JSON, HTML, and XML content. Learn to handle
POST requests, parse URL parameters, set custom response headers,
serve JSONP content, return raw HTML/JavaScript, and create
downloadable text files.
Section 10: Introduction to HtmlService
HtmlService facilitates the creation of web apps and user interfaces. Master
creating HTML pages, serving HTML files, embedding JavaScript, using
templated HTML, serving CSS, communication between client and server,
passing data, incorporating Google Material Design, and serving HTML
with IFrame sandbox mode.
Section 11: Introduction to HtmlOutput
HtmlOutput allows you to serve HTML content programmatically. Learn to
create basic HTML output, set titles, add inline CSS, serve HTML as a web
app, include JavaScript, use templated HTML, change MIME types, and
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
7
create downloadable HTML files with custom fonts and external
JavaScript/CSS.
Section 12: Introduction to TextOutput
TextOutput is your tool for serving text content programmatically. Discover
how to create basic text responses, set content types, return JSON data,
serve text as a web app, handle plain text POST requests, set character
encoding, serve XML data, create downloadable text content, add headers,
and return CSV data.
With this comprehensive guide, you'll unlock the full potential of Google
Apps Script and become a master at automating and integrating various
Google Apps to boost your productivity and streamline your workflows.
Each Section is packed with practical examples, code snippets, and
detailed explanations to ensure your success in leveraging the power of
Google Apps Script. Let's embark on this journey of automation and
efficiency together!
Introduction to CalendarApp
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
8
Google Apps Script, particularly focusing on the versatile CalendarApp
class. Whether you're a seasoned developer or just starting, these tips are
sure to enhance your productivity and scripting prowess. 🌟
● Event Creation: Learn to create events seamlessly in your Google
Calendar. #GoogleAppsScript #EventManagement #Automation
● Event Searching: Master the art of event searching using specific
criteria. #EventSearch #CalendarApp #Scripting
● Event Deletion: Automate the process of deleting unwanted events.
#EventDeletion #GoogleCalendar #Efficiency
● Event Updates: Skillfully modify event times with simple scripts.
#CalendarUpdates #TimeManagement #GoogleScripts
● Recurring Events: Set up recurring events without hassle.
#RecurringEvents #ProductivityHacks #ScriptingLife
● Event Details Retrieval: Fetch and log event details for any given day.
#DataRetrieval #ScriptingMagic #GoogleCalendarAPI
● Guest Management: Add guests to events automatically.
#GuestManagement #AutomatedInvites #GoogleApps
● Privacy Settings: Learn to modify event visibility settings.
#PrivacyControl #CalendarSettings #TechTips
● Calendar ID Retrieval: Effortlessly find and use your calendar ID.
#CalendarID #ScriptingTools #GoogleTech
● Listing Calendars: Compile a list of all accessible calendars and their
IDs. #CalendarList #ScriptingSolutions #GoogleAPI
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
9
Each tip comes with a full explanation and code snippet, making it super
accessible for all skill levels. These insights not only make working with
Google Calendar efficient but also open doors to innovative solutions for
everyday scheduling tasks. 📅
1: Creating an Event
Question: How do you create a simple event in the user's default calendar
using Google Apps Script?
Answer:
function createEvent() {
var calendar = CalendarApp.getDefaultCalendar();
var startTime = new Date('March 15, 2024 15:00:00');
var endTime = new Date('March 15, 2024 16:00:00');
var event = calendar.createEvent('Meeting with Bob', startTime, endTime);
}
2: Finding Events
Question: How can you search for events with a specific title in a calendar?
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
10
Answer:
function findEvents() {
var calendar = CalendarApp.getDefaultCalendar();
var events = calendar.getEvents(new Date('March 1, 2024'), new
Date('March 31, 2024'), {search: 'Meeting'});
return events;
}
Explanation: This script searches the default calendar for events with the
word 'Meeting' in their title, between March 1, 2024, and March 31, 2024.
The getEvents() method is used with a date range and a search term.
3: Deleting an Event
Answer:
function deleteEvent() {
var calendar = CalendarApp.getDefaultCalendar();
var events = calendar.getEvents(new Date('March 1, 2024'), new
Date('March 31, 2024'), {search: 'Unwanted Event'});
if (events.length > 0) {
events[0].deleteEvent();
}
}
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
11
Explanation: This code finds events titled 'Unwanted Event' and deletes the
first occurrence. It's important to handle the case where no events are
found to avoid errors.
4: Updating an Event
Answer:
function updateEventTime() {
var calendar = CalendarApp.getDefaultCalendar();
var events = calendar.getEvents(new Date('March 15, 2024'), new
Date('March 16, 2024'), {search: 'Meeting with Bob'});
if (events.length > 0) {
var newStartTime = new Date('March 15, 2024 17:00:00');
var newEndTime = new Date('March 15, 2024 18:00:00');
events[0].setTime(newStartTime, newEndTime);
}
}
Explanation: This function looks for events titled 'Meeting with Bob' and
updates the start and end times of the first matching event. It's crucial to
check that the event exists before attempting to modify it.
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
12
5: Creating a Recurring Event
Answer:
function createRecurringEvent() {
var calendar = CalendarApp.getDefaultCalendar();
var startTime = new Date('March 15, 2024 09:00:00');
var endTime = new Date('March 15, 2024 10:00:00');
var recurrence =
CalendarApp.newRecurrence().addWeeklyRule().until(new Date('June 15,
2024'));
calendar.createEventSeries('Weekly Team Meeting', startTime, endTime,
recurrence);
}
Question: How can you retrieve and log the details of all events on a
specific day?
Answer:
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
13
function logEventDetails() {
var calendar = CalendarApp.getDefaultCalendar();
var events = calendar.getEventsForDay(new Date('March 15, 2024'));
for (var i = 0; i < events.length; i++) {
Logger.log('Event: ' + events[i].getTitle() + ', Time: ' +
events[i].getStartTime());
}
}
Explanation: This function retrieves all events for March 15, 2024, and logs
their title and start time. The getEventsForDay() method is used to get the
day's events.
Answer:
function addGuestsToEvent() {
var calendar = CalendarApp.getDefaultCalendar();
var events = calendar.getEvents(new Date('March 15, 2024'), new
Date('March 16, 2024'), {search: 'Meeting with Bob'});
if (events.length > 0) {
events[0].addGuest('[email protected]');
}
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
14
}
Explanation: This script finds an event named 'Meeting with Bob' and adds
a guest with the email '[email protected]'. The addGuest() method is
used to add guests to the event.
Answer:
function makeEventPrivate() {
var calendar = CalendarApp.getDefaultCalendar();
var events = calendar.getEvents(new Date('March 15, 2024'), new
Date('March 16, 2024'), {search: 'Meeting with Bob'});
if (events.length > 0) {
events[0].setVisibility(CalendarApp.Visibility.PRIVATE);
}
}
Explanation: This function changes the visibility of the first 'Meeting with
Bob' event to private. The setVisibility() method is employed to modify the
event's visibility setting.
9: Getting Calendar ID
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
15
Question: How do you find and log the ID of the user's default calendar?
Answer:
function logCalendarId() {
var calendar = CalendarApp.getDefaultCalendar();
Logger.log(calendar.getId());
}
Question: How can you list all calendar names and their IDs that the user
has access to?
Answer:
function listAllCalendars() {
var calendars = CalendarApp.getAllCalendars();
for (var i = 0; i < calendars.length; i++) {
Logger.log('Calendar Name: ' + calendars[i].getName() + ', ID: ' +
calendars[i].getId());
}
}
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
16
Explanation: This script uses getAllCalendars() to retrieve all calendars the
user has access to and logs their names and IDs. This can be useful for
identifying specific calendars for more complex operations.
Introduction to DocumentApp
Below are some incredible insights into the world of Google Apps Script,
focusing on the amazing capabilities of the DocumentApp class. If you're
passionate about automating and enhancing your document handling,
these tips are a goldmine! 💡
● Document Creation Magic: Discover how to create Google Docs on
the fly. #GoogleAppsScript #DocumentCreation #CodingLife
● Text Addition Techniques: Learn the art of programmatically adding
text. #TextManipulation #DocumentApp #Automation
● Smart Formatting: Master the skill of formatting text with simple
scripts. #TextFormatting #GoogleDocs #Scripting
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
17
● Table Insertion: Dive into creating organized tables in documents.
#TableInsertion #DocumentAutomation #GoogleScript
● Header Hacks: Effortlessly add headers to your Google Docs.
#HeaderCreation #DocumentDesign #TechTips
● Image Implementation: Insert images with ease using URLs.
#ImageInsertion #GoogleDocsTricks #ScriptingSolutions
● Footer Fundamentals: Learn to append footers for a complete
document. #FooterAddition #GoogleDocs #ScriptingMagic
● Title Transformation: Change document titles programmatically.
#TitleManagement #DocumentApp #TechHacks
● Find and Replace: Automate text replacement in your documents.
#TextReplacement #Automation #GoogleAppsScript
● Content Cleanup: Skillfully remove specific paragraphs from a
document. #ContentManagement #Scripting #GoogleDocs
Each tip includes a full explanation and code snippet, making it super
accessible for all skill levels. Embrace these insights to revolutionize the
way you handle Google Docs, making your workflow smoother and more
efficient. 📝
1: Creating a New Document
Question: How do you create a new Google Document using Google Apps
Script?
Answer:
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
18
function createNewDocument() {
var doc = DocumentApp.create('New Document');
Logger.log(doc.getUrl());
}
Answer:
function addTextToDocument() {
var doc = DocumentApp.openById('YOUR_DOCUMENT_ID');
var body = doc.getBody();
body.appendParagraph('This is a new paragraph.');
}
Explanation: This code snippet opens an existing document using its ID,
gets its body, and then appends a new paragraph with the specified text.
3: Formatting Text
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
19
Question: How do you change the font size and style of a specific
paragraph?
Answer:
function formatText() {
var doc = DocumentApp.openById('YOUR_DOCUMENT_ID');
var body = doc.getBody();
var paragraph = body.getParagraphs()[0];
paragraph.setFontSize(12).setBold(true);
}
4: Inserting a Table
Answer:
function insertTable() {
var doc = DocumentApp.openById('YOUR_DOCUMENT_ID');
var body = doc.getBody();
var table = body.appendTable([['Cell 1', 'Cell 2'], ['Cell 3', 'Cell 4']]);
}
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
20
Explanation: This script adds a table with two rows and two columns to the
document, with each cell containing predefined text.
5: Adding a Header
Answer:
function addHeader() {
var doc = DocumentApp.openById('YOUR_DOCUMENT_ID');
var header = doc.addHeader();
header.appendParagraph('This is a header.');
}
6: Inserting an Image
Answer:
function insertImage() {
var doc = DocumentApp.openById('YOUR_DOCUMENT_ID');
var body = doc.getBody();
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
21
var imageUrl = 'https://example.com/image.png'; // Replace with your
image URL
var image = UrlFetchApp.fetch(imageUrl).getBlob();
body.appendImage(image);
}
Explanation: This script fetches an image from a URL and inserts it into the
document's body. Note that the URL must be publicly accessible.
7: Creating a Footer
Answer:
function addFooter() {
var doc = DocumentApp.openById('YOUR_DOCUMENT_ID');
var footer = doc.addFooter();
footer.appendParagraph('This is a footer.');
}
Explanation: This function adds a footer to the document and then inserts a
paragraph of text into it.
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
22
Answer:
function changeDocumentTitle() {
var doc = DocumentApp.openById('YOUR_DOCUMENT_ID');
doc.setName('New Title');
}
Answer:
function findAndReplaceText() {
var doc = DocumentApp.openById('YOUR_DOCUMENT_ID');
var body = doc.getBody();
body.replaceText('oldText', 'newText');
}
Explanation: This script searches the entire body of the document for
'oldText' and replaces it with 'newText'.
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
23
Question: How can you delete a specific paragraph from a document?
Answer:
function deleteParagraph() {
var doc = DocumentApp.openById('YOUR_DOCUMENT_ID');
var body = doc.getBody();
var paragraph = body.getParagraphs()[1]; // assuming you want to delete
the second paragraph
paragraph.removeFromParent();
}
Introduction to DriveApp
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
24
Below are some powerful insights into the DriveApp class of Google Apps
Script. If you're looking to streamline your Google Drive interactions and
automate file management, these tips will be game-changers! 💼🔧
● Folder Creation Simplified: Learn to create folders instantly.
#GoogleAppsScript #DriveApp #FolderCreation
● Effortless File Uploads: Master the art of uploading text files.
#FileUpload #DriveAutomation #CloudStorage
● File Search Wizardry: Find files by name like a pro. #FileSearch
#DriveAppMagic #GoogleDrive
● File Organization: Move files to folders with ease. #FileManagement
#DriveOrganization #ScriptingSkills
● Smart Sharing: Share files with specific users seamlessly.
#FileSharing #DriveAccess #TechSavvy
● Permission Handling: Set files to public access effortlessly.
#AccessControl #DrivePermissions #GoogleScripts
● File Deletion: Learn to delete files securely. #FileDeletion
#DriveCleanup #Automation
● Folder File Listing: List all files in a folder with a simple script.
#FileListing #DriveApp #Efficiency
● Google Docs Creation: Create Google Docs files directly in Drive.
#GoogleDocs #Scripting #DriveAppTips
● Reading File Contents: Read text file contents easily.
#ContentManagement #FileReading #GoogleDrive
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
25
Each tip comes with a comprehensive explanation and a handy code
snippet, making them accessible for all skill levels. Embrace these insights
to revolutionize your Google Drive usage, enhancing productivity and
workflow efficiency. 📊📁
1: Creating a New Folder
Question: How do you create a new folder in Google Drive using Google
Apps Script?
Answer:
function createNewFolder() {
var folder = DriveApp.createFolder('New Folder');
Logger.log(folder.getUrl());
}
2: Uploading a File
Answer:
function uploadTextFile() {
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
26
var content = 'Hello, World!';
var file = DriveApp.createFile('Example.txt', content,
MimeType.PLAIN_TEXT);
Logger.log(file.getUrl());
}
Explanation: This code snippet creates and uploads a text file named
'Example.txt' with the content 'Hello, World!' to Google Drive. The file URL
is logged afterward.
Question: How do you find files with a specific name in Google Drive?
Answer:
function findFiles() {
var files = DriveApp.getFilesByName('Example.txt');
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getUrl());
}
}
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
27
4: Moving a File to a Folder
Answer:
5: Sharing a File
Answer:
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
28
Explanation: This function shares a file (identified by fileId) with a user
(whose email is userEmail). The addViewer() method gives view access to
the specified user.
Question: How can you change the sharing permissions of a file to 'public'?
Answer:
function makeFilePublic(fileId) {
var file = DriveApp.getFileById(fileId);
file.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.VIEW);
}
7: Deleting a File
Answer:
function deleteFile(fileId) {
var file = DriveApp.getFileById(fileId);
file.setTrashed(true);
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
29
}
Answer:
function listFilesInFolder(folderId) {
var folder = DriveApp.getFolderById(folderId);
var files = folder.getFiles();
while (files.hasNext()) {
var file = files.next();
Logger.log(file.getName());
}
}
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
30
Answer:
function createGoogleDoc() {
var doc = DocumentApp.create('New Document');
DriveApp.getFileById(doc.getId());
}
Explanation: This code snippet creates a new Google Docs file titled 'New
Document' and retrieves it using DriveApp.
Question: How can you read the content of a text file in Drive?
Answer:
function readFileContent(fileId) {
var file = DriveApp.getFileById(fileId);
var content = file.getBlob().getDataAsString();
Logger.log(content);
}
Explanation: This function reads and logs the content of a text file.
getBlob().getDataAsString() is used to get the file's content in string format.
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
31
These questions and answers provide a comprehensive understanding of
various functionalities of the DriveApp class in Google Apps Script,
demonstrating how to manage and interact with files and folders in Google
Drive programmatically.
Introduction to FormApp
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
32
● Retrieving Responses: Learn to gather and analyze form responses
efficiently. #DataCollection #ResponseAnalysis #GoogleScript
● Date Setup: Integrate date collection into your forms.
#Date#FormSetup #TechInnovation
● Form Email Distribution: Send your forms seamlessly via email.
#EmailIntegration #FormSharing #DigitalCommunication
● Form Theme Customization: Personalize your forms with unique
themes. #ThemeCustomization #FormDesign #GoogleApps
● Linear Scale Questions: Enhance your surveys with linear scale
questions. #SurveyCreation #Scale#UserFeedback
● Item Deletion in Forms: Manage your form's content effectively by
removing items. #ContentManagement #FormEditing
#ScriptingSolutions
Each tip comes with a full explanation and a code snippet, making it easy
to understand and apply. Embrace these strategies to elevate your Google
Forms, enhancing user experience and data collection accuracy. 📝📈
1: Creating a New Form
Question: How do you create a new Google Form using Google Apps
Script?
Answer:
function createNewForm() {
var form = FormApp.create('New Survey');
Logger.log(form.getPublishedUrl());
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
33
}
Answer:
function addMultipleChoiceQuestion() {
var form = FormApp.openById('YOUR_FORM_ID');
form.addMultipleChoiceItem()
.setTitle('What is your favorite color?')
.setChoiceValues(['Red', 'Blue', 'Green']);
}
Answer:
function createFormResponse() {
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
34
var form = FormApp.openById('YOUR_FORM_ID');
var formResponse = form.createResponse();
var items = form.getItems();
var itemResponse =
items[0].asMultipleChoiceItem().createResponse('Red');
formResponse.withItemResponse(itemResponse);
formResponse.submit();
}
Answer:
function addSectionHeader() {
var form = FormApp.openById('YOUR_FORM_ID');
form.addSectionHeaderItem()
.setTitle('Section 1: Personal Information');
}
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
35
Explanation: This script adds a section header titled 'Section 1: Personal
Information' to the form.
Answer:
function getFormResponses() {
var form = FormApp.openById('YOUR_FORM_ID');
var responses = form.getResponses();
for (var i = 0; i < responses.length; i++) {
Logger.log(responses[i].getTimestamp());
}
}
Explanation: This function fetches all responses to the form and logs the
timestamp of each response.
Answer:
function addDateQuestion() {
var form = FormApp.openById('YOUR_FORM_ID');
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
36
form.addDateItem()
.setTitle('What is your birthdate?');
}
Explanation: This script adds a date to the form, asking for the respondent's
birthdate.
Answer:
function sendFormByEmail(email) {
var form = FormApp.openById('YOUR_FORM_ID');
MailApp.sendEmail(email, 'Please fill out this form', 'Link to the form: ' +
form.getPublishedUrl());
}
Explanation: This function sends an email with a link to the form to the
specified email address using the MailApp class.
Answer:
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
37
function changeFormTheme() {
var form = FormApp.openById('YOUR_FORM_ID');
form.setTheme(FormApp.Theme.CAT);
}
Answer:
function addLinearScaleQuestion() {
var form = FormApp.openById('YOUR_FORM_ID');
form.addLinearScaleItem()
.setTitle('Rate your satisfaction (1-5)')
.setBounds(1, 5);
}
Explanation: This function adds a linear scale to the form, with a scale from
1 to 5.
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
38
Answer:
function deleteFormItem(itemIndex) {
var form = FormApp.openById('YOUR_FORM_ID');
var items = form.getItems();
if (items.length > itemIndex) {
form.deleteItem(items[itemIndex]);
}
}
Explanation: This script deletes an item from the form based on its index in
the item array. The existence of the item at the specified index is checked
before deletion to prevent errors.
Introduction to GmailApp
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
39
I'm excited to share some key insights into Google Apps Script, particularly
diving into the powerful GmailApp class. If you're aiming to automate and
optimize your email tasks, these tips are invaluable! 📧💻
● Seamless Email Sending: Discover the ease of sending emails
programmatically. #GoogleAppsScript #GmailApp #EmailAutomation
● Efficient Email Search: Master the technique of searching emails by
subject. #EmailSearch #Automation #TechTips
● Label Application: Learn to organize emails with custom labels.
#EmailOrganization #GmailLabels #Scripting
● Marking Read: Automate marking emails as read.
#EmailManagement #ReadStatus #GoogleScripts
● Unread Emails Tracking: Fetch all your unread emails in a snap.
#UnreadEmails #InboxManagement #TechSolutions
● Emails with Attachments: Send attachments effortlessly via email.
#EmailAttachments #DriveIntegration #ProductivityHacks
● Draft Creation: Create email drafts with just a few lines of code.
#DraftEmails #GmailApp #Coding
● Email Deletion: Manage your inbox by programmatically deleting
threads. #InboxCleanup #EmailDeletion #ScriptingMagic
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
40
● Sender Email Count: Count emails from specific senders easily.
#EmailAnalytics #SenderTracking #GmailTips
● Fetching Email Content: Retrieve the latest email content in a thread.
#EmailContent #MessageRetrieval #TechInnovation
Each tip is packed with a full explanation and a code snippet, making them
easy to understand and implement. Harness these strategies to elevate
your Gmail experience, enhancing both efficiency and effectiveness in
email handling. 🚀📬
1: Sending an Email
Question: How do you send a basic email using Google Apps Script?
Answer:
function sendEmail() {
GmailApp.sendEmail('[email protected]', 'Subject', 'Hello, this is the
email body.');
}
2: Searching Emails
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
41
Question: How can you search for emails with a specific subject?
Answer:
function searchEmails() {
var threads = GmailApp.search('subject:"Your Subject Here"');
return threads;
}
Answer:
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
42
Explanation: This function adds a label to an email thread. It checks if the
label exists, creates it if it doesn't, and then applies it to the thread.
Answer:
function markEmailAsRead(threadId) {
var thread = GmailApp.getThreadById(threadId);
thread.markRead();
}
Answer:
function getUnreadEmails() {
var threads = GmailApp.search('is:unread');
return threads;
}
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
43
Explanation: This function fetches all unread email threads using the
search query 'is:unread'. It returns an array of thread objects.
Answer:
function sendEmailWithAttachment() {
var file = DriveApp.getFileById('YOUR_FILE_ID'); // Replace with your file
ID
GmailApp.sendEmail('[email protected]', 'Subject', 'Email body', {
attachments: [file.getAs(MimeType.PDF)] // Assuming the file is a PDF
});
}
Explanation: This script sends an email with a file attachment. The file is
fetched from Google Drive using its ID, and attached as a PDF.
Answer:
function createDraft() {
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
44
GmailApp.createDraft('[email protected]', 'Draft Subject', 'This is the
draft body.');
}
Answer:
function deleteEmailThread(threadId) {
var thread = GmailApp.getThreadById(threadId);
thread.moveToTrash();
}
Explanation: This code snippet moves an email thread to the trash using
moveToTrash() on the thread object.
Question: How do you count the number of emails received from a specific
email address?
Answer:
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
45
function countEmailsFromSender(senderEmail) {
var threads = GmailApp.search('from:' + senderEmail);
return threads.length;
}
Question: How can you fetch the body content of the latest email in a
thread?
Answer:
function fetchLatestEmailBody(threadId) {
var thread = GmailApp.getThreadById(threadId);
var messages = thread.getMessages();
var latestMessage = messages[messages.length - 1];
return latestMessage.getBody();
}
Explanation: This script retrieves the latest message from an email thread
and returns its body content. It accesses the last message in the thread's
message array.
Introduction to MailApp
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
46
Apps Script MailApp
📧
Script: Exploring MailApp! 📧
Elevate Your Email Game with Google Apps
I'm excited to share some key insights into Google Apps Script, specifically
the versatile MailApp class. If you're keen on automating and enhancing
your email operations, these tips are just for you! 🚀💻
● Simplified Email Sending: Discover the ease of sending basic emails.
#GoogleAppsScript #MailApp #EmailAutomation
● HTML Email Mastery: Dive into sending emails with HTML content.
#HTMLemails #TechTips #Scripting
● Multiple Recipients Handling: Learn to send emails to multiple people
effortlessly. #MassEmails #CommunicationSkills #GoogleScript
● Cc and Bcc Inclusion: Master adding CC and BCC recipients to your
emails. #EmailManagement #GmailHacks #Scripting
● Emails with Attachments: Send attachments seamlessly in emails.
#EmailAttachments #DriveIntegration #GoogleApps
● Inline Images in Emails: Enhance your emails with inline images.
#EmailDesign #VisualCommunication #TechInnovation
● Email Quota Check: Keep track of your email sending quota.
#QuotaManagement #MailApp #Efficiency
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
47
● Rich Text Emailing: Send emails with rich text formatting. #RichText
#EmailFormatting #DigitalCommunication
● Setting Reply-To Addresses: Customize your reply-to address in
emails. #EmailCustomization #ProfessionalCommunication
#GoogleScripts
● Advanced Email Options: Explore sending emails with both plain text
and HTML bodies. #EmailOptions #TechSavvy #ScriptingMastery
Each tip comes with a detailed explanation and a code snippet, making
them accessible for all levels. Embrace these strategies to transform your
Gmail experience, making your email communication more efficient and
impactful. 🌟📬
1: Sending a Basic Email
Question: How do you send a basic email using Google Apps Script?
Answer:
function sendBasicEmail() {
MailApp.sendEmail('[email protected]', 'Subject', 'This is the email
body.');
}
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
48
2: Sending an Email with HTML Body
Question: How can you send an email with HTML content in the body?
Answer:
function sendHtmlEmail() {
var htmlBody = '<p>This is an <b>HTML</b> email.</p>';
MailApp.sendEmail('[email protected]', 'Subject', '', {htmlBody:
htmlBody});
}
Explanation: This code sends an email with HTML content. The HTML is
specified in the htmlBody parameter of the sendEmail method.
Answer:
function sendEmailToMultipleRecipients() {
var recipients = '[email protected],[email protected]';
MailApp.sendEmail(recipients, 'Subject', 'This is the email body.');
}
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
49
Explanation: This function sends an email to multiple recipients. The
recipients' email addresses are separated by commas.
Question: How can you send an email with CC and BCC recipients?
Answer:
function sendEmailWithCcBcc() {
var cc = '[email protected]';
var bcc = '[email protected]';
MailApp.sendEmail('[email protected]', 'Subject', 'This is the email
body.', {cc: cc, bcc: bcc});
}
Answer:
function sendEmailWithAttachment() {
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
50
var file = DriveApp.getFileById('YOUR_FILE_ID'); // Replace with your file
ID
MailApp.sendEmail('[email protected]', 'Subject', 'Please see
attached file.', {
attachments: [file.getAs(MimeType.PDF)] // Assuming the file is a PDF
});
}
Explanation: This function sends an email with a file attachment. The file is
retrieved from Google Drive using its ID and attached to the email.
Answer:
function sendEmailWithInlineImage() {
var htmlBody = 'Inline image: <img src="cid:imageKey">';
var blob = DriveApp.getFileById('IMAGE_FILE_ID').getBlob(); // Replace
with your image file ID
MailApp.sendEmail({
to: '[email protected]',
subject: 'Subject with inline image',
htmlBody: htmlBody,
inlineImages: {
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
51
imageKey: blob
}
});
}
Explanation: This script sends an HTML email with an inline image. The
image is referenced using a content ID (cid) within the HTML and is passed
in the inlineImages object.
Question: How do you check the remaining daily quota for sending emails?
Answer:
function checkEmailQuota() {
var remainingQuota = MailApp.getRemainingDailyQuota();
Logger.log('Remaining email quota: ' + remainingQuota);
}
Explanation: This function retrieves the remaining daily quota for sending
emails using MailApp.getRemainingDailyQuota().
Question: How can you send an email with rich text formatting?
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
52
Answer:
function sendRichTextEmail() {
var body = 'This is <b>bold</b> and this is <i>italic</i>.';
MailApp.sendEmail('[email protected]', 'Rich Text Email', '',
{htmlBody: body});
}
Explanation: This script sends an email where the body contains rich text
formatting. HTML tags are used for formatting, and the content is sent as
an HTML body.
Answer:
function setReplyToAddress() {
MailApp.sendEmail({
to: '[email protected]',
subject: 'Subject',
body: 'This is the email body.',
replyTo: '[email protected]'
});
}
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
53
Explanation: This function sends an email with a specific reply-to address
using the replyTo option in the sendEmail method.
Question: How can you send an email with both plain text and HTML
bodies?
Answer:
function sendEmailWithAdvancedOptions() {
var plainBody = 'This is the plain text body.';
var htmlBody = '<p>This is the <b>HTML</b> body.</p>';
MailApp.sendEmail({
to: '[email protected]',
subject: 'Subject',
body: plainBody,
htmlBody: htmlBody
});
}
Explanation: This script sends an email with both plain text and HTML
bodies. The email client of the recipient will display the format it supports or
prefers.
Introduction to SpreadsheetApp
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
54
Apps Script SpreadsheetApp
🚀 Mastering Google Sheets Automation with
Secrets! 🚀
Google Apps Script: Unveiling SpreadsheetApp
I'm excited to share some deep dive insights into Google Apps Script,
especially the incredibly powerful SpreadsheetApp class. If you're
passionate about automating and revolutionizing your Google Sheets
experience, these tips are tailor-made for you! 📊💻
● Effortless Spreadsheet Creation: Learn to create new spreadsheets
on the go. #GoogleAppsScript #SpreadsheetApp #Automation
● Smart Data Entry: Dive into adding data to specific cells easily.
#DataEntry #TechTips #GoogleSheets
● Reading Range Data: Master extracting data from ranges.
#DataExtraction #SpreadsheetMagic #Scripting
● Appending Data Dynamically: Append rows of data seamlessly.
#DataAppending #SheetsAutomation #GoogleTech
● Formula Integration: Set up formulas in cells programmatically.
#FormulasInSheets #EfficiencyHacks #Scripting
● Customizing Cell Appearance: Change cell background colors with
scripts. #CellFormatting #VisualData #GoogleSheets
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
55
● Data Find & Replace: Automate finding and replacing spreadsheet
data. #DataManipulation #SpreadsheetApp #TechSkills
● Adding New Sheets: Easily add new sheets to your spreadsheets.
#SheetManagement #GoogleApps #Productivity
● Range Protection: Learn to protect ranges from unwanted edits.
#DataProtection #SheetsSecurity #ScriptingSolutions
● Automated Data Sorting: Sort data ranges with ease. #DataSorting
#SpreadsheetOrganization #GoogleAppsScript
Each tip comes with a detailed explanation and a handy code snippet,
making it super accessible for all skill levels. Embrace these insights to
transform your Google Sheets, bringing efficiency and innovation to your
data handling. 📈📝
Answer:
function createNewSpreadsheet() {
Logger.log(spreadsheet.getUrl());
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
56
}
Answer:
function addDataToCell() {
var spreadsheet =
SpreadsheetApp.openById('YOUR_SPREADSHEET_ID');
sheet.getRange('A1').setValue('Hello, World!');
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
57
3: Reading Data from a Range
Answer:
function readDataFromRange() {
var spreadsheet =
SpreadsheetApp.openById('YOUR_SPREADSHEET_ID');
return values;
Explanation: This function reads and returns the data from a range (A1:B2)
in the active sheet of the specified spreadsheet. getValues() returns a 2D
array of the range's contents.
Answer:
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
58
function appendRow() {
var spreadsheet =
SpreadsheetApp.openById('YOUR_SPREADSHEET_ID');
Explanation: This script appends a new row with three cells ('New', 'Row',
'Data') to the bottom of the active sheet.
Answer:
function setFormulaInCell() {
var spreadsheet =
SpreadsheetApp.openById('YOUR_SPREADSHEET_ID');
sheet.getRange('C1').setFormula('=SUM(A1:B1)');
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
59
}
Answer:
function changeCellBackgroundColor() {
var spreadsheet =
SpreadsheetApp.openById('YOUR_SPREADSHEET_ID');
sheet.getRange('A1').setBackground('yellow');
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
60
Question: How do you find and replace data in a spreadsheet?
Answer:
function findAndReplaceData() {
var spreadsheet =
SpreadsheetApp.openById('YOUR_SPREADSHEET_ID');
sheet.createTextFinder('oldData').replaceAllWith('newData');
Answer:
function addNewSheet() {
var spreadsheet =
SpreadsheetApp.openById('YOUR_SPREADSHEET_ID');
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
61
spreadsheet.insertSheet('New Sheet');
Explanation: This code snippet adds a new sheet titled 'New Sheet' to the
specified spreadsheet.
9: Protecting a Range
Answer:
function protectRange() {
var spreadsheet =
SpreadsheetApp.openById('YOUR_SPREADSHEET_ID');
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
62
Explanation: This script protects a range (A1:B2) in the active sheet,
preventing it from being edited by other users. The protection is given a
description for clarity.
Answer:
function sortRange() {
var spreadsheet =
SpreadsheetApp.openById('YOUR_SPREADSHEET_ID');
Explanation: This function sorts the data in the range A1:B10 in the active
sheet based on the values in the first column (column 1) in ascending
order.
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
63
Introduction to SlidesApp
🌟
Google Apps Script: A Journey with SlidesApp!
I'm excited to share some enriching insights into Google Apps Script,
focusing on the dynamic SlidesApp class. For those looking to automate
and creatively enhance their Google Slides presentations, these tips are a
goldmine! 📈🎨
● Seamless Presentation Creation: Learn how to create new
presentations instantly. #GoogleAppsScript #SlidesApp
#PresentationCreation
● Dynamic Text Boxes: Master the art of adding text boxes to your
slides. #TextManipulation #PresentationDesign #TechTips
● Slide Background Customization: Change slide backgrounds to make
your presentations stand out. #VisualDesign #SlidesApp
#GoogleSlides
● Incorporating Images: Enhance your slides with images from the web.
#ImageIntegration #CreativePresentations #Scripting
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
64
● Slide Duplication: Duplicate slides efficiently for consistent formatting.
#SlideManagement #PresentationSkills #GoogleScript
● Utilizing Predefined Layouts: Add slides with specific layouts to
streamline design. #LayoutsInSlides #DesignEfficiency #TechHacks
● Text Replacement in Slides: Automate finding and replacing text
across your presentation. #TextAutomation #SlidesApp #GoogleTech
● Creating Hyperlinks: Turn your text into clickable links within slides.
#Hyperlinks #InteractivePresentations #DigitalSolutions
● Styling Text: Learn to style text for emphasis and clarity. #TextStyle
#FontManagement #PresentationTips
● Deleting Slides: Manage your slide deck by removing unnecessary
slides. #SlideEditing #PresentationCleanup #ScriptingMagic
Each tip comes with a detailed explanation and a practical code snippet,
making it super accessible for all skill levels. Embrace these strategies to
revolutionize your Google Slides presentations, bringing both efficiency and
creativity to your storytelling. 📊💡
1: Creating a New Presentation
Answer:
function createNewPresentation() {
var presentation = SlidesApp.create('New Presentation');
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
65
Logger.log(presentation.getUrl());
}
Answer:
function addTextBox() {
var presentation = SlidesApp.openById('YOUR_PRESENTATION_ID');
var slide = presentation.getSlides()[0]; // Get the first slide
slide.insertTextBox('Hello, Slides!');
}
Answer:
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
66
function changeSlideBackgroundColor() {
var presentation = SlidesApp.openById('YOUR_PRESENTATION_ID');
var slide = presentation.getSlides()[0];
slide.getBackground().setSolidFill('#00FF00'); // Sets the background to
green
}
Explanation: This function changes the background color of the first slide to
green using a hex color code.
4: Adding an Image
Answer:
function addImageToSlide() {
var presentation = SlidesApp.openById('YOUR_PRESENTATION_ID');
var slide = presentation.getSlides()[0];
var imageUrl = 'https://example.com/image.png'; // Replace with your
image URL
slide.insertImage(imageUrl);
}
Explanation: This script adds an image to the first slide of the presentation.
The image is fetched from the specified URL.
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
67
5: Duplicating a Slide
Answer:
function duplicateSlide() {
var presentation = SlidesApp.openById('YOUR_PRESENTATION_ID');
var slide = presentation.getSlides()[0];
presentation.insertSlide(1, slide); // Duplicate the first slide and insert it as
the second slide
}
Explanation: This function duplicates the first slide and inserts the duplicate
as the second slide in the presentation.
Question: How can you add a new slide with a specific layout?
Answer:
function addSlideWithLayout() {
var presentation = SlidesApp.openById('YOUR_PRESENTATION_ID');
var layouts = presentation.getLayouts();
var layout = layouts[0]; // Choose a layout; here we select the first layout
presentation.appendSlide(layout);
}
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
68
Explanation: This script adds a new slide to the presentation using a
predefined layout, selected from the available layouts.
Answer:
function replaceTextInSlides() {
var presentation = SlidesApp.openById('YOUR_PRESENTATION_ID');
presentation.replaceAllText('oldText', 'newText');
}
8: Creating a Hyperlink
Question: How can you create a text box with a hyperlink in a slide?
Answer:
function createHyperlink() {
var presentation = SlidesApp.openById('YOUR_PRESENTATION_ID');
var slide = presentation.getSlides()[0];
var textBox = slide.insertTextBox('OpenAI');
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
69
var textRange = textBox.getText();
textRange.setLinkUrl('https://www.openai.com');
}
Explanation: This script adds a text box to the first slide and sets the text
'OpenAI' with a hyperlink to 'https://www.openai.com'.
Question: How do you change the font size and make text bold in a text
box?
Answer:
function changeTextStyle() {
var presentation = SlidesApp.openById('YOUR_PRESENTATION_ID');
var slide = presentation.getSlides()[0];
var textBox = slide.insertTextBox('Bold and Large Text');
var textRange = textBox.getText();
textRange.setFontSize(24).setBold(true);
}
Explanation: This function creates a text box with the text 'Bold and Large
Text', sets the font size to 24, and makes the text bold.
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
70
Question: How can you delete a specific slide from a presentation?
Answer:
function deleteSlide() {
var presentation = SlidesApp.openById('YOUR_PRESENTATION_ID');
var slides = presentation.getSlides();
presentation.removeSlide(slides[1]); // Remove the second slide
}
Explanation: This script removes the second slide from the presentation.
The slide is identified by its index in the array returned by getSlides().
Introduction to ContentService
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
71
I'm excited to share some cutting-edge insights into Google Apps Script,
focusing on the versatile ContentService class. If you're aiming to
streamline your web interactions and data serving techniques, these
nuggets of wisdom are just what you need! 💻🔧
● Plain Text Content Serving: Discover how to serve plain text via web
apps. #GoogleAppsScript #ContentService #WebDevelopment
Question: How do you create a basic web app that serves plain text content
using Google Apps Script?
Answer:
function doGet() {
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
72
Explanation: This script uses doGet() to handle HTTP GET requests to the
web app. It uses ContentService.createTextOutput() to return a plain text
response 'Hello, World!'.
Introduction to HtmlService
Dive into the fascinating world of Google Apps Script today, particularly the
versatile HtmlService class. For those looking to add a creative and
interactive touch to their Google Sheets, Docs, or web apps, these insights
are a treasure trove! 💻🌈
● Simple HTML Creation: Learn to create and serve simple HTML
pages. #GoogleAppsScript #HtmlService #WebDevelopment
● Serving HTML Files: Master the art of serving HTML files from your
script project. #HTML #Coding #Scripting
● JavaScript Integration: Embed JavaScript in your HTML pages for
dynamic content. #JavaScript #WebDesign #DigitalCreation
● Dynamic Templated HTML: Use templated HTML for personalized
content delivery. #TemplatedHTML #CustomWeb #TechTips
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
73
● Styling with CSS: Bring life to your pages with CSS styling. #CSS
#WebStyling #CreativeCoding
● Server-Side Function Calls: Connect HTML elements to Google
Script functions. #FunctionCalls #InteractiveDesign #Scripting
● Client-Server Data Transfer: Learn to pass data from client to server
seamlessly. #DataTransfer #WebApps #GoogleScripts
● Material Design Implementation: Incorporate Google's Material
Design for a sleek look. #MaterialDesign #UIUX #DesignInTech
● Custom UI for Google Sheets: Create unique user interfaces within
Google Sheets. #CustomUI #GoogleSheets #SpreadsheetMagic
● IFrame Sandbox Mode: Serve secure HTML content in IFrame
sandbox mode. #IFrame #WebSecurity #SandboxMode
Question: How do you create and serve a simple HTML page using Google
Apps Script?
Answer:
function doGet() {
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
74
return HtmlService.createHtmlOutput('<h1>Hello World!</h1>');
Question: How can you serve an HTML file stored in the script project?
Answer:
function doGet() {
return html;
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
75
3: Embedding JavaScript in HTML Service
Answer:
function doGet() {
return html;
Question: How can you use templated HTML to dynamically insert values
into a page?
Answer:
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
76
function doGet() {
template.userName = 'Alice';
return template.evaluate();
Answer:
function doGet() {
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
77
return html;
Explanation: This script embeds CSS directly into the HTML output,
changing the color of the text to blue.
Question: How can you call a server-side Google Apps Script function from
HTML served by HtmlService?
Answer:
function doGet() {
return html;
function myFunction() {
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
78
}
Question: How do you pass data from the HTML page to a server-side
function?
Answer:
function doGet() {
return html;
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
79
function processName(name) {
Explanation: This code includes a text input and a button in the HTML.
When the button is clicked, it calls a JavaScript function submitName(),
which retrieves the input value and passes it to the server-side function
processName.
Answer:
function doGet() {
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
80
return html;
Answer:
function showCustomUi() {
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
81
10: Serving HTML with IFrame Sandbox Mode
Question: How can you serve HTML content in IFrame sandbox mode?
Answer:
function doGet() {
return html;
Explanation: This script serves HTML content using IFrame as the sandbox
mode, which provides a secure and isolated environment for the content.
Introduction to HtmlOutput
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
82
🌟
into HtmlOutput! 🌟
Exploring the Versatility of Google Apps Script: A Deep Dive
Below are some enriching insights into Google Apps Script, especially the
dynamic HtmlOutput class. Perfect for those looking to elevate their web
app experiences with interactive and responsive HTML interfaces! 💻🌐
● Basic HTML Output Creation: Learn to craft simple yet impactful
HTML outputs. #GoogleAppsScript #HtmlOutput #WebDevelopment
● Enhancing Pages with Titles: Discover the art of setting titles for your
HTML outputs. #PageTitles #WebDesign #CodingTips
● Styling with Inline CSS: Inject life into pages with CSS styles.
#InlineCSS #Styling #CreativeCoding
● Web App Serving Techniques: Master serving HTML content as a
web app. #WebApps #Scripting #DigitalInnovation
● JavaScript Inclusion: Integrate JavaScript for dynamic and interactive
content. #JavaScript #WebInteraction #ScriptingMagic
● Dynamic Templated HTML: Utilize templated HTML for flexible
content rendering. #TemplatedHTML #DynamicContent
#TechSolutions
● Custom MIME Types: Tailor MIME types for specific content needs.
#MimeType #WebStandards #TechTips
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
83
● Creating Downloadable HTML: Design HTML outputs for easy
downloading. #DownloadableContent #HtmlService #DigitalSolutions
● Incorporating Custom Fonts: Enhance the aesthetic appeal with
custom fonts. #WebFonts #DesignInTech #UserExperience
● Embedding External Resources: Leverage external JS and CSS for
enriched functionalities. #ExternalResources #WebDesign
#CodingExcellence
Each tip comes with a full explanation and a practical code snippet, making
them super accessible for all skill levels. Embrace these strategies to
transform your Google Apps Script projects into interactive, user-friendly
web experiences. 🚀📊
1: Creating Basic HTML Output
Question: How do you create a basic HTML output in Google Apps Script?
Answer:
function createBasicHtmlOutput() {
return htmlOutput;
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
84
Explanation: This function creates a basic HTML output with a heading tag
(<h1>). HtmlService.createHtmlOutput() is used to generate the HTML
content.
Question: How can you set the title of an HTML output page?
Answer:
function setHtmlOutputTitle() {
return htmlOutput;
Explanation: This script sets the title of the HTML output to 'My Custom
Page' using the setTitle() method.
Answer:
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
85
function addInlineCssToHtmlOutput() {
return HtmlService.createHtmlOutput(html);
Explanation: This function creates HTML output with inline CSS that sets
the background color of the body element.
Question: How can you serve HTML output as a web app in Google Apps
Script?
Answer:
function doGet() {
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
86
Explanation: This script uses the special function doGet() to serve HTML
content when the web app URL is accessed. It's the entry point for a web
app in Google Apps Script.
Answer:
function htmlOutputWithJavascript() {
return HtmlService.createHtmlOutput(html);
Answer:
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
87
function useTemplatedHtml() {
template.name = 'Alice';
return template.evaluate();
Answer:
function includeCustomFonts() {
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
88
return HtmlService.createHtmlOutput(html);
Explanation: This function includes a link to the Google Fonts API for the
'Roboto' font and sets it as the font family in the CSS.
Question: How do you embed external JavaScript and CSS files in HTML
output?
Answer:
function embedExternalJsCss() {
return HtmlService.createHtmlOutput(html);
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
89
Explanation: This script embeds external JavaScript and CSS by including
their respective <script> and <link> tags in the HTML output.
These questions and answers illustrate a variety of uses for the HtmlOutput
class in Google Apps Script, showing how to create interactive and
dynamic HTML content for web apps and user interfaces.
Introduction to TextOutput
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
90
● CSV Data Responses: Serve CSV formatted data effectively. #CSV
#DataFormats #ScriptingMastery
Each tip comes with an in-depth explanation and a code snippet, making
them highly accessible and implementable for various web-based projects.
Embrace these strategies to enhance your web app responses, making
your text data handling more efficient and versatile. 🚀📊
1: Creating Basic Text Output
Question: How do you create a basic text output in Google Apps Script?
Answer:
function createBasicTextOutput() {
return textOutput;
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
91
Question: How can you set the content type for a text output to JSON?
Answer:
function setContentTypeJson() {
.setMimeType(ContentService.MimeType.JSON);
return textOutput;
Explanation: This code snippet creates a text output and sets its MIME type
to JSON using setMimeType(). This is useful when returning
JSON-formatted strings in web apps.
Answer:
function returnJson() {
var data = {
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
92
message: 'Hello, JSON!'
};
return ContentService.createTextOutput(jsonString)
.setMimeType(ContentService.MimeType.JSON);
Question: How can you serve text output as a web app in Google Apps
Script?
Answer:
function doGet() {
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
93
Explanation: This script uses the doGet() function to serve text content as a
response in a web app. It's the standard way to handle GET requests in a
Google Apps Script web app.
Question: How do you create and serve XML data as text output?
Answer:
function serveXmlData() {
return ContentService.createTextOutput(xmlData)
.setMimeType(ContentService.MimeType.XML);
Question: How can you return CSV formatted data as text output?
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
94
Answer:
function returnCsvData() {
return ContentService.createTextOutput(csvData)
.setMimeType(ContentService.MimeType.CSV);
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
95
Learn more about JavaScript with Examples and Source Code. Google Apps Script
and Workspace Laurence Svekis Courses https://basescripts.com/
96