Class Form

Форма

Форма, содержащая общие свойства и элементы. Свойства включают заголовок, настройки и место хранения ответов. Элементы включают элементы вопросов, такие как флажки или переключатели, а элементы макета относятся к таким вещам, как разрывы страниц. Доступ к формам можно получить или создать из Form App .

// Open a form by ID and create a new spreadsheet.
const form = FormApp.openById('1234567890abcdefghijklmnopqrstuvwxyz');
const ss = SpreadsheetApp.create('Spreadsheet Name');

// Update form properties via chaining.
form.setTitle('Form Name')
    .setDescription('Description of form')
    .setConfirmationMessage('Thanks for responding!')
    .setAllowResponseEdits(true)
    .setAcceptingResponses(false);

// Update the form's response destination.
form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());

Методы

Метод Тип возврата Краткое описание
add Checkbox Grid Item() Checkbox Grid Item Добавляет новый элемент вопроса, представленный в виде сетки столбцов и строк, который позволяет респонденту выбирать несколько вариантов ответа в каждой строке из последовательности флажков.
add Checkbox Item() Checkbox Item Добавляет новый элемент вопроса, который позволяет респонденту выбрать один или несколько флажков, а также необязательное поле «Другое».
add Date Item() Date Item Добавляет новый элемент вопроса, который позволяет респонденту указать дату.
add Date Time Item() Date Time Item Добавляет новый элемент вопроса, который позволяет респонденту указать дату и время.
add Duration Item() Duration Item Добавляет новый элемент вопроса, который позволяет респонденту указать промежуток времени.
add Editor(emailAddress) Form Добавляет данного пользователя в список редакторов Form .
add Editor(user) Form Добавляет данного пользователя в список редакторов Form .
add Editors(emailAddresses) Form Добавляет заданный массив пользователей в список редакторов Form .
add Grid Item() Grid Item Добавляет новый элемент вопроса, представленный в виде сетки столбцов и строк, который позволяет респонденту выбрать один вариант ответа в каждой строке из последовательности переключателей.
add Image Item() Image Item Добавляет новый элемент макета, отображающий изображение.
add List Item() List Item Добавляет новый элемент вопроса, который позволяет респонденту выбрать один вариант из раскрывающегося списка.
add Multiple Choice Item() Multiple Choice Item Добавляет новый элемент вопроса, который позволяет респонденту выбрать один вариант из списка переключателей или необязательного поля «другое».
add Page Break Item() Page Break Item Добавляет новый элемент макета, который отмечает начало страницы.
add Paragraph Text Item() Paragraph Text Item Добавляет новый элемент вопроса, который позволяет респонденту ввести блок текста.
add Published Reader(emailAddress) Form Добавляет данного пользователя в список отвечающих на Form .
add Published Reader(user) Form Добавляет данного пользователя в список отвечающих на Form .
add Published Readers(emailAddresses) Form Добавляет заданный массив пользователей в список отвечающих на Form .
add Rating Item() Rating Item Добавляет новый элемент вопроса, который позволяет респонденту поставить оценку.
add Scale Item() Scale Item Добавляет новый элемент вопроса, который позволяет респонденту выбрать один вариант из пронумерованной последовательности переключателей.
add Section Header Item() Section Header Item Добавляет новый элемент макета, который визуально указывает начало раздела.
add Text Item() Text Item Добавляет новый элемент вопроса, который позволяет респонденту ввести одну строку текста.
add Time Item() Time Item Добавляет новый элемент вопроса, который позволяет респонденту указать время суток.
add Video Item() Video Item Добавляет новый элемент макета, отображающий видео.
can Edit Response() Boolean Определяет, отображает ли форма ссылку для редактирования ответа после его отправки.
collects Email() Boolean Определяет, собирает ли форма адреса электронной почты респондентов.
create Response() Form Response Создает новый ответ на форму.
delete All Responses() Form Удаляет все отправленные ответы из хранилища ответов формы.
delete Item(index) void Удаляет элемент по заданному индексу среди всех элементов формы.
delete Item(item) void Удаляет данный элемент.
delete Response(responseId) Form Удаляет один ответ из хранилища ответов формы.
get Confirmation Message() String Получает сообщение подтверждения формы.
get Custom Closed Form Message() String Получает настраиваемое сообщение, которое отображается, если форма не принимает ответы, или пустую строку, если настраиваемое сообщение не задано.
get Description() String Получает описание формы.
get Destination Id() String Получает идентификатор места назначения ответа формы.
get Destination Type() Destination Type Получает тип назначения ответа формы.
get Edit Url() String Получает URL-адрес, который можно использовать для доступа к режиму редактирования формы.
get Editors() User[] Получает список редакторов для этой Form .
get Id() String Получает идентификатор формы.
get Item By Id(id) Item Получает элемент с заданным идентификатором.
get Items() Item[] Получает массив всех элементов формы.
get Items(itemType) Item[] Получает массив всех элементов заданного типа.
get Published Readers() User[] Получает список ответивших на эту Form .
get Published Url() String Получает URL-адрес, который можно использовать для ответа на форму.
get Response(responseId) Form Response Получает один ответ формы на основе его идентификатора ответа.
get Responses() Form Response[] Получает массив всех ответов формы.
get Responses(timestamp) Form Response[] Получает массив всех ответов формы после заданной даты и времени.
get Shuffle Questions() Boolean Определяет, является ли порядок вопросов на каждой странице формы случайным.
get Summary Url() String Получает URL-адрес, который можно использовать для просмотра сводки ответов формы.
get Title() String Получает заголовок формы.
has Limit One Response Per User() Boolean Определяет, допускает ли форма только один ответ для каждого респондента.
has Progress Bar() Boolean Определяет, отображает ли форма индикатор выполнения.
has Respond Again Link() Boolean Определяет, отображает ли форма ссылку для отправки другого ответа после того, как респондент заполнит форму.
is Accepting Responses() Boolean Определяет, принимает ли форма в данный момент ответы.
is Published() Boolean Определяет, опубликована ли форма.
is Publishing Summary() Boolean Определяет, отображает ли форма ссылку для просмотра сводки ответов после того, как респондент заполнит форму.
is Quiz() Boolean Определяет, является ли форма тестом.
move Item(from, to) Item Перемещает элемент по заданному индексу среди всех элементов формы в другой заданный индекс.
move Item(item, toIndex) Item Перемещает заданный элемент в заданный индекс среди всех элементов формы.
remove Destination() Form Отключает форму от текущего места назначения ответа.
remove Editor(emailAddress) Form Удаляет данного пользователя из списка редакторов Form .
remove Editor(user) Form Удаляет данного пользователя из списка редакторов Form .
remove Published Reader(emailAddress) Form Удаляет данного пользователя из списка отвечающих на Form .
remove Published Reader(user) Form Удаляет данного пользователя из списка отвечающих на Form .
set Accepting Responses(enabled) Form Устанавливает, принимает ли форма в данный момент ответы.
set Allow Response Edits(enabled) Form Определяет, отображает ли форма ссылку для редактирования ответа после его отправки.
set Collect Email(collect) Form Определяет, собирает ли форма адреса электронной почты респондентов.
set Confirmation Message(message) Form Устанавливает сообщение подтверждения формы.
set Custom Closed Form Message(message) Form Устанавливает сообщение, которое будет отображаться, если форма не принимает ответы.
set Description(description) Form Устанавливает описание формы.
set Destination(type, id) Form Устанавливает место назначения, в котором сохраняются ответы формы.
set Is Quiz(enabled) Form Устанавливает, является ли форма тестом.
set Limit One Response Per User(enabled) Form Устанавливает, допускает ли форма только один ответ для каждого респондента.
set Progress Bar(enabled) Form Устанавливает, имеет ли форма индикатор выполнения.
set Published(enabled) Form Устанавливает, публикуется ли форма.
set Publishing Summary(enabled) Form Определяет, отображает ли форма ссылку для просмотра сводки ответов после отправки формы респондентом.
set Show Link To Respond Again(enabled) Form Определяет, отображает ли форма ссылку для отправки другого ответа после того, как респондент заполнит форму.
set Shuffle Questions(shuffle) Form Определяет, является ли порядок вопросов на каждой странице формы случайным.
set Title(title) Form Устанавливает заголовок формы.
shorten Form Url(url) String Преобразует длинный URL-адрес формы в короткий URL-адрес.
submit Grades(responses) Form Отправляет оценки за заданные ответы FormResponse.
supports Advanced Responder Permissions() Boolean Определяет, поддерживает ли форма публикацию.

Подробная документация

add Checkbox Grid Item()

Добавляет новый элемент вопроса, представленный в виде сетки столбцов и строк, который позволяет респонденту выбирать несколько вариантов ответа в каждой строке из последовательности флажков.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a checkbox grid item.
const item = form.addCheckboxGridItem();

item.setTitle('Where did you celebrate New Year\'s?');

// Sets the grid's rows and columns.
item.setRows(['New York', 'San Francisco', 'London']).setColumns([
  '2014', '2015', '2016', '2017'
]);

Возвращаться

Checkbox Grid Item — вновь созданный элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Checkbox Item()

Добавляет новый элемент вопроса, который позволяет респонденту выбрать один или несколько флажков, а также необязательное поле «Другое».

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a checkbox item.
const item = form.addCheckboxItem();

// Sets the title of the checkbox item to 'Do you prefer cats or dogs?'
item.setTitle('Do you prefer cats or dogs?');

// Sets the choices.
item.setChoiceValues(['Cats', 'Dogs']);

Возвращаться

Checkbox Item — вновь созданный элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Date Item()

Добавляет новый элемент вопроса, который позволяет респонденту указать дату.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a date item.
const item = form.addDateItem();

// Sets the title to 'When were you born?'
item.setTitle('When were you born?');

// Sets the description for the date item.
item.setHelpText('Some helper text.');

Возвращаться

Date Item — вновь созданный элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Date Time Item()

Добавляет новый элемент вопроса, который позволяет респонденту указать дату и время.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a question with date and time inputs.
const item = form.addDateTimeItem();

// Sets the title to 'When were you born?'
item.setTitle('When were you born?');

// Sets the question as required.
item.setRequired(true);

Возвращаться

Date Time Item — вновь созданный элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Duration Item()

Добавляет новый элемент вопроса, который позволяет респонденту указать промежуток времени.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a question with a duration input.
const item = form.addDurationItem();

// Sets the title to 'How long can you hold your breath?'
item.setTitle('How long can you hold your breath?');

// Sets the question as required.
item.setRequired(true);

Возвращаться

Duration Item — вновь созданный элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Editor(emailAddress)

Добавляет данного пользователя в список редакторов Form . Если пользователь уже был в списке зрителей или ответивших, этот метод удаляет пользователя из списка.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Adds editor to the form.
// TODO(developer): replace the emailAddress.
form.addEditor('editor@uni.edu');

Параметры

Имя Тип Описание
email Address String Адрес электронной почты пользователя, которого требуется добавить.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Editor(user)

Добавляет данного пользователя в список редакторов Form . Если пользователь уже был в списке зрителей или ответивших, этот метод удаляет пользователя из списка.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const oldForm = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Gets the editors from the old form.
const users = oldForm.getEditors();

// Creates a new form.
const newForm = FormApp.create('New form');

// Adds the editors to a new form.
users.forEach(user => newForm.addEditor(user));

Параметры

Имя Тип Описание
user User Представление добавляемого пользователя.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Editors(emailAddresses)

Добавляет заданный массив пользователей в список редакторов Form . Если кто-либо из пользователей уже был в списке зрителей, этот метод удаляет его из списка зрителей.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Adds editors to the form.
// TODO(developer): replace the emailAddress.
form.addPublishedReaders(['editor1@uni.edu', 'editor2@uni.edu']);

Параметры

Имя Тип Описание
email Addresses String[] Массив адресов электронной почты пользователей, которых нужно добавить.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Grid Item()

Добавляет новый элемент вопроса, представленный в виде сетки столбцов и строк, который позволяет респонденту выбрать один вариант ответа в каждой строке из последовательности переключателей.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a multiple choice grid.
const item = form.addGridItem();

// Sets the title to 'Rate your interests.'
item.setTitle('Rate your interests');

// Sets the grid's rows and columns.
item.setRows(['Cars', 'Computers', 'Celebrities']).setColumns([
  'Boring', 'So-so', 'Interesting'
]);

Возвращаться

Grid Item — вновь созданный элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Image Item()

Добавляет новый элемент макета, отображающий изображение.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds an image item.
const item = form.addImageItem();

// Gets the Google icon to use as the image.
const img = UrlFetchApp.fetch(
    'https://fonts.gstatic.com/s/i/productlogos/googleg/v6/web-24dp/logo_googleg_color_1x_web_24dp.png',
);

// Sets the image, title, and description for the item.
item.setTitle('Google icon').setHelpText('Google icon').setImage(img);

Возвращаться

Image Item — вновь созданный элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add List Item()

Добавляет новый элемент вопроса, который позволяет респонденту выбрать один вариант из раскрывающегося списка.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a dropdown list to the form.
const item = form.addListItem();

// Sets the title to 'Do you prefer cats or dogs?'
item.setTitle('Do you prefer cats or dogs?');

// Sets the description to 'This is description text...'
item.setHelpText('This is description text...');

// Creates and adds choices to the dropdown list.
item.setChoices([item.createChoice('dog'), item.createChoice('cat')]);

Возвращаться

List Item — вновь созданный элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Multiple Choice Item()

Добавляет новый элемент вопроса, который позволяет респонденту выбрать один вариант из списка переключателей или необязательного поля «другое».

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a multiple choice item to the form.
const item = form.addMultipleChoiceItem();

// Sets the title.
item.setTitle('What is your favorite ice cream flavor?');

// Creates some choice items.
const vanilla = item.createChoice('vanilla');
const chocolate = item.createChoice('chocolate');
const strawberry = item.createChoice('strawberry');

// Sets the choices.
item.setChoices([vanilla, chocolate, strawberry]);

Возвращаться

Multiple Choice Item — вновь созданный элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Page Break Item()

Добавляет новый элемент макета, который отмечает начало страницы.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds page break items to create a second and third page for the form.
const pageTwo = form.addPageBreakItem();
const pageThree = form.addPageBreakItem();

// Sets the titles for the pages.
pageTwo.setTitle('Page two');
pageThree.setTitle('Page three');

// Upon completion of the first page, sets the form to navigate to the third
// page.
pageTwo.setGoToPage(pageThree);

// Upon completion of the second page, sets the form to navigate back to the
// first page.
pageThree.setGoToPage(FormApp.PageNavigationType.RESTART);

Возвращаться

Page Break Item — вновь созданный элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Paragraph Text Item()

Добавляет новый элемент вопроса, который позволяет респонденту ввести блок текста.

// Opens the form by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds the paragraph text item.
const item = form.addParagraphTextItem();

// Sets the title to 'What is your address?'
item.setTitle('What is your address?');

Возвращаться

Paragraph Text Item — вновь созданный элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Published Reader(emailAddress)

Добавляет данного пользователя в список отвечающих на Form . Если пользователь уже был в списке редакторов или читателей, этот метод не имеет никакого эффекта.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Adds responder to the form.
// TODO(developer): replace the emailAddress.
form.addPublishedReader('responder@uni.edu');

Параметры

Имя Тип Описание
email Address String Адрес электронной почты пользователя, которого требуется добавить.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Published Reader(user)

Добавляет данного пользователя в список отвечающих на Form . Если пользователь уже был в списке редакторов или читателей, этот метод не имеет никакого эффекта.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const oldForm = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Gets the responders from the old form.
const users = oldForm.getPublishedReaders();

// Creates a new form.
const newForm = FormApp.create('New form');

// Adds the responders to a new form.
users.forEach(user => newForm.addPublishedReader(user));

Параметры

Имя Тип Описание
user User Представление добавляемого пользователя.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Published Readers(emailAddresses)

Добавляет заданный массив пользователей в список отвечающих на Form . Если пользователь уже был в списке редакторов или читателей, этот метод не имеет никакого эффекта.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Adds responders to the form.
// TODO(developer): replace the emailAddress.
form.addPublishedReaders(['responder1@uni.edu', 'responder2@uni.edu']);

Параметры

Имя Тип Описание
email Addresses String[] Массив адресов электронной почты пользователей, которых нужно добавить.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Rating Item()

Добавляет новый элемент вопроса, который позволяет респонденту поставить оценку.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds the rating item.
const item = form.addRatingItem();

Возвращаться

Rating Item — вновь созданный элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Scale Item()

Добавляет новый элемент вопроса, который позволяет респонденту выбрать один вариант из пронумерованной последовательности переключателей.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds the scale item.
const item = form.addScaleItem();

// Sets the title of the scale item to 'Choose a number.'
item.setTitle('Choose a number');

// Sets the scale to 1-5.
item.setBounds(1, 5);

// Sets the label for the lower and upper bounds.
item.setLabels('Lowest', 'Highest');

Возвращаться

Scale Item — вновь созданный элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Section Header Item()

Добавляет новый элемент макета, который визуально указывает начало раздела.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds the section heading item.
const item = form.addSectionHeaderItem();

// Sets the title to 'Title of new section.'
item.setTitle('Title of new section');

// Sets the description.
item.setHelpText('Description of new section');

Возвращаться

Section Header Item — вновь созданный элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Text Item()

Добавляет новый элемент вопроса, который позволяет респонденту ввести одну строку текста.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a single-line text item.
const item = form.addTextItem();

// Sets the title to 'What is your name?'
item.setTitle('What is your name?');

Возвращаться

Text Item — вновь созданный элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Time Item()

Добавляет новый элемент вопроса, который позволяет респонденту указать время суток.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a question with a time input.
const item = form.addTimeItem();

// Sets the title to 'What time do you usually wake up in the morning?'
item.setTitle('What time do you usually wake up in the morning?');

Возвращаться

Time Item — вновь созданный элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Video Item()

Добавляет новый элемент макета, отображающий видео.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a video item.
const item = form.addVideoItem();

// Sets the title, description, and video.
item.setTitle('YouTube video')
    .setHelpText('Send content automatically via Google Sheets and Apps Script')
    .setVideoUrl('https://youtu.be/xxgQr-jSu9o');

// Sets the alignment to the center.
item.setAlignment(FormApp.Alignment.CENTER);

Возвращаться

Video Item — вновь созданный элемент.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

can Edit Response()

Определяет, отображает ли форма ссылку для редактирования ответа после его отправки.

Независимо от этого параметра, метод Form Response.getEditResponseUrl() позволяет автору сценария, имеющему доступ к редактированию формы, создать URL-адрес, который можно использовать для редактирования ответа.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Checks if the form displays a link to edit a response after submitting it.
// The default is false. To let people edit their responses, use
// form.setAllowResponseEdits(true).
const edit = form.canEditResponse();

// If the form doesn't let people edit responses, logs false to the console.
console.log(edit);

Возвращаться

Booleantrue , если в форме отображается ссылка «Изменить ответ»; false если это не так.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

collects Email()

Определяет, собирает ли форма адреса электронной почты респондентов.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to not collect respondents' email addresses.
form.setCollectEmail(false);

// Checks whether the form collects respondents' email addresses and logs it to
// the console.
const bool = form.collectsEmail();

console.log(bool);

Возвращаться

Booleantrue , если форма собирает адреса электронной почты; false если это не так.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

create Response()

Создает новый ответ на форму. Чтобы ответить на элемент вопроса, создайте Item Response из элемента, затем прикрепите его к этому ответу формы, вызвав Form Response.withItemResponse(response) . Чтобы сохранить собранный ответ, вызовите Form Response.submit() .

Возвращаться

Form Response — вновь созданный ответ формы.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

delete All Responses()

Удаляет все отправленные ответы из хранилища ответов формы. Этот метод не удаляет копии ответов, хранящиеся во внешнем месте назначения ответов (например, в электронной таблице), но очищает сводное представление формы.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

delete Item(index)

Удаляет элемент по заданному индексу среди всех элементов формы. Выдает исключение сценария, если по данному индексу не существует элемента.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets all the items from the form.
const items = form.getItems();

// Finds the index of a paragraph text item and deletes it by the item's index.
const index = items.findIndex(
    (item) => item.getType() === FormApp.ItemType.PARAGRAPH_TEXT,
);
if (index !== -1) {
  form.deleteItem(index);
}

Параметры

Имя Тип Описание
index Integer Индекс элемента среди всех элементов формы.

Броски

Error — если по данному индексу не существует элемента

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

delete Item(item)

Удаляет данный элемент. Выдает исключение сценария, если элемент уже был удален.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets all of the items from the form.
const items = form.getItems();

// Finds a paragraph text item and deletes it.
const item = items.find(
    (item) => item.getType() === FormApp.ItemType.PARAGRAPH_TEXT,
);
if (item) {
  form.deleteItem(item);
}

Параметры

Имя Тип Описание
item Item Элемент, который необходимо удалить.

Броски

Error — если элемент не существует в форме

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

delete Response(responseId)

Удаляет один ответ из хранилища ответов формы. Этот метод не удаляет копии ответов, хранящиеся во внешнем месте назначения ответов (например, в электронной таблице), но удаляет ответ из сводного представления формы. Идентификатор ответа можно получить с помощью Form Response.getId() .

Параметры

Имя Тип Описание
response Id String Идентификатор ответа формы, который необходимо удалить.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Confirmation Message()

Получает сообщение подтверждения формы.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the confirmation message to display after someone submits the form.
form.setConfirmationMessage('You successfully submitted the form.');

// Gets the confirmation message and logs it to the console.
const message = form.getConfirmationMessage();

console.log(message);

Возвращаться

String — сообщение подтверждения формы.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Custom Closed Form Message()

Получает настраиваемое сообщение, которое отображается, если форма не принимает ответы, или пустую строку, если настраиваемое сообщение не задано.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets a custom closed form message to display to the user when the form
// no longer accepts responses.
form.setCustomClosedFormMessage('The form is no longer accepting responses.');

// Gets the custom message set for the form and logs it to the console.
const message = form.getCustomClosedFormMessage();

console.log(message);

Возвращаться

String — настраиваемое сообщение, отображаемое, если форма не принимает ответы, или пустая строка, если настраиваемое сообщение не задано.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Description()

Получает описание формы.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form description.
form.setDescription('This is the form description.');

// Gets the form description and logs it to the console.
const description = form.getDescription();

console.log(description);

Возвращаться

String — описание формы.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Destination Id()

Получает идентификатор места назначения ответа формы.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Creates a spreadsheet to use as the response destination.
const ss = SpreadsheetApp.create('Test_Spreadsheet');

// Updates the form's response destination.
form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());

// Gets the ID of the form's response destination and logs it to the console.
const destinationId = form.getDestinationId();

console.log(destinationId);

Возвращаться

String — идентификатор места назначения ответа формы.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Destination Type()

Получает тип назначения ответа формы.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc1234556/edit',
);

// Gets the type of the form's response destination and logs it to the console.
const destinationType = form.getDestinationType().name();

console.log(destinationType);

Возвращаться

Destination Type — тип назначения ответа формы.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Edit Url()

Получает URL-адрес, который можно использовать для доступа к режиму редактирования формы.

// Opens the form by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the URL that accesses the form's edit mode and logs it to the console.
const url = form.getEditUrl();

console.log(url);

Возвращаться

String — URL-адрес для редактирования формы.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Editors()

Получает список редакторов для этой Form .

Возвращаться

User[] — Массив пользователей с разрешением на редактирование.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Id()

Получает идентификатор формы.

// Opens the form by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the ID of the form and logs it to the console.
const id = form.getId();

console.log(id);

Возвращаться

String — идентификатор формы.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Item By Id(id)

Получает элемент с заданным идентификатором. Возвращает значение null , если идентификатор не соответствует элементу в форме.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the ID of the first item on the form.
const itemId = form.getItems()[0].getId();

// Gets the item from the ID.
const item = form.getItemById(itemId);

// Gets the name of the item type and logs it to the console.
const type = item.getType().name();

console.log(type);

Параметры

Имя Тип Описание
id Integer Идентификатор предмета.

Возвращаться

Item — элемент с заданным идентификатором или null , если элемент не существует в форме.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Items()

Получает массив всех элементов формы.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the list of items in the form.
const items = form.getItems();

// Gets the type for each item and logs them to the console.
const types = items.map((item) => item.getType().name());

console.log(types);

Возвращаться

Item[] — Массив всех элементов формы.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Items(itemType)

Получает массив всех элементов заданного типа.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets a list of all checkbox items on the form.
const items = form.getItems(FormApp.ItemType.CHECKBOX);

// Gets the title of each checkbox item and logs them to the console.
const checkboxItemsTitle = items.map(
    (item) => item.asCheckboxItem().getTitle(),
);
console.log(checkboxItemsTitle);

Параметры

Имя Тип Описание
item Type Item Type Тип элементов, которые необходимо получить.

Возвращаться

Item[] — Массив всех элементов этого типа.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Published Readers()

Получает список ответивших на эту Form .

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Gets the responders for the form.
const users = form.getPublishedReaders();
users.forEach(user => console.log(user.getEmail()));

Возвращаться

User[] — Массив пользователей с разрешением респондента.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Published Url()

Получает URL-адрес, который можно использовать для ответа на форму.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the URL to respond to the form and logs it to the console.
const url = form.getPublishedUrl();
console.log(url);

Возвращаться

String — URL-адрес для ответа на форму.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Response(responseId)

Получает один ответ формы на основе его идентификатора ответа. Идентификаторы ответов можно получить из Form Response.getId() .

Параметры

Имя Тип Описание
response Id String Идентификатор ответа формы.

Возвращаться

Form Response — ответ формы.

Броски

Error — если ответа не существует

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Responses()

Получает массив всех ответов формы.

Возвращаться

Form Response[] — Массив всех ответов формы.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Responses(timestamp)

Получает массив всех ответов формы после заданной даты и времени.

Параметры

Имя Тип Описание
timestamp Date Самая ранняя дата и время, для которых должны быть возвращены ответы формы.

Возвращаться

Form Response[] — Список ответов формы.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Shuffle Questions()

Определяет, является ли порядок вопросов на каждой странице формы случайным.

Возвращаться

Booleantrue , если порядок вопросов на каждой странице формы рандомизирован; false если нет.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Summary Url()

Получает URL-адрес, который можно использовать для просмотра сводки ответов формы. Если set Publishing Summary(enabled) не установлено значение true , только пользователи с разрешением на редактирование формы смогут получить доступ к URL-адресу.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// Opens the form by its URL.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the URL to view a summary of the form's responses and logs it to the
// console.
const url = form.getSummaryUrl();
console.log(url);

Возвращаться

String — URL-адрес для просмотра сводки ответов.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Title()

Получает заголовок формы.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the title of the form to 'For_Testing.'
form.setTitle('For_Testing');

// Gets the title of the form and logs it to the console.
const title = form.getTitle();
console.log(title);

Возвращаться

String — заголовок формы.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

has Limit One Response Per User()

Определяет, допускает ли форма только один ответ для каждого респондента. Если значение true , сценарий вообще не может отправлять ответы формы.

Возвращаться

Booleantrue , если форма допускает только один ответ для каждого респондента; false если нет.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

has Progress Bar()

Определяет, отображает ли форма индикатор выполнения.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// Opens the form by its URL.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Displays the progress bar on the form.
form.setProgressBar(true);

// Checks if the form displays a progress bar and logs it to the console.
console.log(form.hasProgressBar());

Возвращаться

Booleantrue , если в форме отображается индикатор выполнения; false если это не так.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

Определяет, отображает ли форма ссылку для отправки другого ответа после того, как респондент заполнит форму.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to display a link to submit another
// response after someone submits the form.
form.setShowLinkToRespondAgain(true);

// Checks if the form displays a 'Submit another response' link and logs it to
// the console.
console.log(form.hasRespondAgainLink());

Возвращаться

Booleantrue , если в форме отображается ссылка «Отправить еще один ответ»; false если это не так.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

is Accepting Responses()

Определяет, принимает ли форма в данный момент ответы. Оно перезаписывается при изменении состояния публикации формы.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to accept responses.
form.setAcceptingResponses(true);

// Checks if the form is accepting responses or not and logs it to the console.
const accepting = form.isAcceptingResponses();
console.log(accepting);

Возвращаться

Booleantrue если форма принимает ответы; false если это не так.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

is Published()

Определяет, опубликована ли форма.

Эта функция доступна только для форм, поддерживающих публикацию. Используйте supports Advanced Responder Permissions() чтобы проверить, поддерживает ли форма публикацию.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Checks whether the form is published or not and logs it to the console.
console.log(form.isPublished());

Возвращаться

Booleantrue если форма опубликована; false если это не так.

Броски

Error — если вызывается на неподдерживаемых формах.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

is Publishing Summary()

Определяет, отображает ли форма ссылку для просмотра сводки ответов после того, как респондент заполнит форму.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to display a link to a summary of
// the responses after someone submits the form.
form.setPublishingSummary(true);

// Checks if the form displays a "See previous responses" link and logs it to
// the console.
const publishingLink = form.isPublishingSummary();
console.log(publishingLink);

Возвращаться

Booleantrue , если в форме отображается ссылка «Просмотреть предыдущие ответы»; false если это не так.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

is Quiz()

Определяет, является ли форма тестом.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form as a quiz.
form.setIsQuiz(true);

// Checks if the form is a quiz or not and logs it to the console.
console.log(form.isQuiz());

Возвращаться

Booleantrue если форма принимает ответы; false если это не так.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

move Item(from, to)

Перемещает элемент по заданному индексу среди всех элементов формы в другой заданный индекс. Выдает исключение сценария, если to выходит за пределы.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Moves the first item to be the last item.
form.moveItem(0, form.getItems().length - 1);

Параметры

Имя Тип Описание
from Integer Текущий индекс элемента среди всех элементов формы.
to Integer Новый индекс элемента среди всех элементов формы.

Возвращаться

Item — элемент, который был перемещен.

Броски

Error — если любой индекс выходит за пределы.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

move Item(item, toIndex)

Перемещает заданный элемент в заданный индекс среди всех элементов формы. Выдает исключение сценария, если данный индекс выходит за пределы.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the first item.
const item = form.getItems()[0];

// Moves the item to be the last item.
form.moveItem(item, form.getItems().length - 1);

Параметры

Имя Тип Описание
item Item Предмет для перемещения.
to Index Integer Новый индекс элемента среди всех элементов формы.

Возвращаться

Item — элемент, который был перемещен.

Броски

Error — если индекс выходит за пределы.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

remove Destination()

Отключает форму от текущего места назначения ответа. В несвязанном бывшем пункте назначения по-прежнему сохраняются копии всех предыдущих ответов. Все формы, включая те, у которых явно не указан пункт назначения, сохраняют копии ответов в хранилище ответов формы . Если форма в настоящее время не имеет места назначения ответа, этот метод не имеет никакого эффекта.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Opens a spreadsheet to use for the response destination.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Updates the form's response destination to the spreadsheet.
form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());

// Unlinks the form from the spreadsheet.
form.removeDestination();

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

remove Editor(emailAddress)

Удаляет данного пользователя из списка редакторов Form . Этот метод не блокирует доступ пользователей к Form , если они принадлежат к классу пользователей, имеющих общий доступ, например, если Form используется во всем домене пользователя или если Form находится на общем диске, к которому пользователь может получить доступ.

Для файлов на Диске это также удаляет пользователя из списка зрителей и ответчиков.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Removes the editor from the form.
// TODO(developer): replace the emailAddress.
form.removeEditor('editor@uni.edu');

Параметры

Имя Тип Описание
email Address String Адрес электронной почты пользователя, которого необходимо удалить.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

remove Editor(user)

Удаляет данного пользователя из списка редакторов Form . Этот метод не блокирует доступ пользователей к Form , если они принадлежат к классу пользователей, имеющих общий доступ, например, если Form используется во всем домене пользователя или если Form находится на общем диске, к которому пользователь может получить доступ.

Для файлов на Диске это также удаляет пользователя из списка зрителей.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const form1 = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Gets the editors from the form.
const users = form1.getEditors();

// Opens another form.
// TODO(developer): Replace the URL with your own.
const form2 = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Removes editors from the form.
users.forEach(user => form2.removeEditor(user));

Параметры

Имя Тип Описание
user User Представление пользователя, которого нужно удалить.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

remove Published Reader(emailAddress)

Удаляет данного пользователя из списка отвечающих на Form . Этот метод не блокирует доступ пользователей к Form , если они принадлежат к классу пользователей, имеющих общий доступ, например, если Form используется во всем домене пользователя или если Form находится на общем диске, к которому пользователь может получить доступ.

Для файлов на Диске это также удаляет пользователя из списка читателей и редакторов.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Removes the responders from the form.
// TODO(developer): replace the emailAddress.
form.removePublishedReader('responder1@uni.edu');

Параметры

Имя Тип Описание
email Address String Адрес электронной почты пользователя, которого необходимо удалить.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

remove Published Reader(user)

Удаляет данного пользователя из списка отвечающих на Form . Этот метод не блокирует доступ пользователей к Form , если они принадлежат к классу пользователей, имеющих общий доступ, например, если Form используется во всем домене пользователя или если Form находится на общем диске, к которому пользователь может получить доступ.

Для файлов на Диске это также удаляет пользователя из списка читателей и редакторов.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const form1 = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Gets the responders from the form.
const users = form1.getPublishedReaders();

// Opens another form.
// TODO(developer): Replace the URL with your own.
const form2 = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Removes responders from the form.
users.forEach(user => form2.removePublishedReader(user));

Параметры

Имя Тип Описание
user User Представление пользователя, которого нужно удалить.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Accepting Responses(enabled)

Устанавливает, принимает ли форма в данный момент ответы. По умолчанию для новых форм установлено значение true . Состояние перезаписывается при изменении состояния публикации формы.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to accept responses.
form.setAcceptingResponses(true);

// Checks whether the form is accepting responses or not and logs it to the
// console.
console.log(form.isAcceptingResponses());

Параметры

Имя Тип Описание
enabled Boolean true , если форма должна принимать ответы; false если этого не должно быть.

Возвращаться

Form — Эта Form для связывания.

Броски

Error — если включено в неопубликованной форме.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Allow Response Edits(enabled)

Определяет, отображает ли форма ссылку для редактирования ответа после его отправки. По умолчанию для новых форм установлено значение false .

Независимо от этого параметра, метод Form Response.getEditResponseUrl() позволяет автору сценария, имеющему разрешение на редактирование формы, генерировать URL-адрес, который можно использовать для редактирования ответа.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Shows "Edit your response" link after someone submits the form.
form.setAllowResponseEdits(true);

// Checks whether the option to edit the form after a user submits it is set to
// true or not and logs it to the console.
console.log(form.canEditResponse());

Параметры

Имя Тип Описание
enabled Boolean true , если в форме должна отображаться ссылка «Изменить ответ»; false если нет.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Collect Email(collect)

Определяет, собирает ли форма адреса электронной почты респондентов. По умолчанию для новых форм установлено значение false .

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to collect respondents' email addresses.
form.setCollectEmail(true);

// Checks whether the value is set to true or false and logs it to the console.
const collect = form.collectsEmail();
console.log(collect);

Параметры

Имя Тип Описание
collect Boolean true , если форма должна собирать адреса электронной почты; false если это не так.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Confirmation Message(message)

Устанавливает сообщение подтверждения формы.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets a custom confirmation message to display after someone submits the form.
form.setConfirmationMessage('Your form has been successfully submitted.');

// Gets the confirmation message set for the form and logs it to the console.
const message = form.getConfirmationMessage();
console.log(message);

Параметры

Имя Тип Описание
message String Новое подтверждающее сообщение формы.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Custom Closed Form Message(message)

Устанавливает сообщение, которое будет отображаться, если форма не принимает ответы. Если сообщение не задано, в форме используется сообщение по умолчанию.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to not accept responses.
form.setAcceptingResponses(false);

// Sets a custom closed form message to display to the user.
form.setCustomClosedFormMessage('The form is no longer accepting responses.');

// Gets the custom message set for the form and logs it to the console.
const message = form.getCustomClosedFormMessage();
console.log(message);

Параметры

Имя Тип Описание
message String Сообщение, отображаемое, если форма не принимает ответы.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Description(description)

Устанавливает описание формы.

Параметры

Имя Тип Описание
description String Новое описание формы.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Destination(type, id)

Устанавливает место назначения, в котором сохраняются ответы формы. Все формы, включая те, у которых явно не указан пункт назначения, сохраняют копии ответов в хранилище ответов формы .

Параметры

Имя Тип Описание
type Destination Type Тип назначения ответа формы.
id String Идентификатор места назначения ответа формы.

Возвращаться

Form — Эта Form для связывания.

Броски

Error — если указанный идентификатор пункта назначения недействителен.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Is Quiz(enabled)

Устанавливает, является ли форма тестом. По умолчанию для новых форм установлено значение false .

Оцениваемые вопросы разрешены только в тестах, поэтому установка значения false приведет к удалению всех параметров оценки из всех вопросов.

Настройки теста доступны только в новом пользовательском интерфейсе Forms; создание формы викторины позволяет форме использовать новый пользовательский интерфейс.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Makes the form a quiz.
form.setIsQuiz(true);

// Checks whether the form is a quiz or not and logs it to the console.
console.log(form.isQuiz());

Параметры

Имя Тип Описание
enabled Boolean true , если для формы должны быть включены функции теста; false если нет.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Limit One Response Per User(enabled)

Устанавливает, допускает ли форма только один ответ для каждого респондента. По умолчанию для новых форм установлено значение false . Если для значения установлено значение true , сценарий вообще не сможет отправлять ответы формы.

Параметры

Имя Тип Описание
enabled Boolean true , если форма должна разрешать только один ответ от каждого респондента; false если нет.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Progress Bar(enabled)

Устанавливает, имеет ли форма индикатор выполнения. По умолчанию для новых форм установлено значение false .

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Displays the progress bar on the form.
form.setProgressBar(true);

// Checks whether the form has a progress bar and logs it to the console.
console.log(form.hasProgressBar());

Параметры

Имя Тип Описание
enabled Boolean true , если в форме отображается индикатор выполнения; false если это не так.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Published(enabled)

Устанавливает, публикуется ли форма. По умолчанию для новых форм установлено значение true .

Эта функция доступна только для форм, поддерживающих публикацию. Используйте supports Advanced Responder Permissions() чтобы проверить, поддерживает ли форма публикацию.

Форму необходимо опубликовать, чтобы она была доступна респондентам. Этот метод заменяет вызовы для set Accepting Responses(enabled) .

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Publishes the form before sharing it.
form.setPublished(true);

// Checks whether the form is published or not and logs it to the console.
console.log(form.isPublished());

Параметры

Имя Тип Описание
enabled Boolean true , если форма должна быть опубликована, false если нет.

Возвращаться

Form — Эта Form для связывания.

Броски

Error — если вызывается на неподдерживаемых формах.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Publishing Summary(enabled)

Определяет, отображает ли форма ссылку для просмотра сводки ответов после отправки формы респондентом. По умолчанию для новых форм установлено значение false .

Параметры

Имя Тип Описание
enabled Boolean true , если в форме должна отображаться ссылка «Просмотреть предыдущие ответы»; false если нет.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Show Link To Respond Again(enabled)

Определяет, отображает ли форма ссылку для отправки другого ответа после того, как респондент заполнит форму. По умолчанию для новых форм установлено значение true .

Параметры

Имя Тип Описание
enabled Boolean true , если в форме должна отображаться ссылка «Отправить другой ответ»; false если нет.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Shuffle Questions(shuffle)

Определяет, является ли порядок вопросов на каждой странице формы случайным.

Параметры

Имя Тип Описание
shuffle Boolean true , если порядок вопросов на каждой странице формы должен быть рандомизирован; false если нет.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Title(title)

Устанавливает заголовок формы.

Параметры

Имя Тип Описание
title String Новое название формы.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

shorten Form Url(url)

Преобразует длинный URL-адрес формы в короткий URL-адрес. Выдает исключение, если длинный URL-адрес не принадлежит Google Forms.

Параметры

Имя Тип Описание
url String URL-адрес, который нужно сократить.

Возвращаться

String — URL-адрес в формате http://goo.gl/forms/1234 .

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

submit Grades(responses)

Отправляет оценки за заданные ответы FormResponse.

Если ваш код включает триггер on Form Submit , вызов submit Grades() запускает условие on Form Submit и вызывает бесконечный цикл. Чтобы предотвратить бесконечный цикл, добавьте код, который проверяет, существуют ли оценки, перед вызовом submit Grades() .

Параметры

Имя Тип Описание
responses Form Response[] Массив всех ответов формы.

Возвращаться

Form — Эта Form для связывания.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

supports Advanced Responder Permissions()

Определяет, поддерживает ли форма публикацию. Этот метод используется для определения доступности set Published(enabled) и is Published() , а также разрешений ответчика.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Checks whether the form supports publishing or not and logs it to the
// console.
console.log(form.supportsAdvancedResponderPermissions());

Возвращаться

Booleantrue , если форма поддерживает публикацию; false если это не так.

Авторизация

Сценарии, использующие этот метод, требуют авторизации с одной или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

Устаревшие методы


,
Форма

Форма, которая содержит общие свойства и элементы. Свойства включают заголовок, настройки и где хранятся ответы. Элементы включают элементы вопросов, такие как флажки или радиосвязи, в то время как элементы макета относятся к таким вещам, как разрывы страниц. Формы можно получить доступ или создать из Form App .

// Open a form by ID and create a new spreadsheet.
const form = FormApp.openById('1234567890abcdefghijklmnopqrstuvwxyz');
const ss = SpreadsheetApp.create('Spreadsheet Name');

// Update form properties via chaining.
form.setTitle('Form Name')
    .setDescription('Description of form')
    .setConfirmationMessage('Thanks for responding!')
    .setAllowResponseEdits(true)
    .setAcceptingResponses(false);

// Update the form's response destination.
form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());

Методы

Метод Возврат тип Краткое описание
add Checkbox Grid Item() Checkbox Grid Item Добавляет новый элемент вопроса, представленный в виде сетки столбцов и строк, который позволяет респонденту выбрать несколько вариантов на строку из последовательности флажков.
add Checkbox Item() Checkbox Item Добавляет новый элемент вопроса, который позволяет респонденту выбрать один или несколько флажков, а также дополнительное поле «Другое».
add Date Item() Date Item Добавляет новый элемент вопроса, который позволяет респонденту указать дату.
add Date Time Item() Date Time Item Добавляет новый элемент вопроса, который позволяет респонденту указать дату и время.
add Duration Item() Duration Item Добавляет новый элемент вопроса, который позволяет респонденту указать время.
add Editor(emailAddress) Form Добавляет данного пользователя в список редакторов для Form .
add Editor(user) Form Добавляет данного пользователя в список редакторов для Form .
add Editors(emailAddresses) Form Добавляет заданный массив пользователей в список редакторов для Form .
add Grid Item() Grid Item Добавляет новый элемент вопроса, представленный в виде сетки столбцов и строк, который позволяет респонденту выбрать один выбор на строку из последовательности радиопроизводительных кнопок.
add Image Item() Image Item Добавляет новый элемент макета, который отображает изображение.
add List Item() List Item Добавляет новый элемент вопроса, который позволяет респонденту выбрать один выбор из раскрывающегося списка.
add Multiple Choice Item() Multiple Choice Item Добавляет новый элемент вопроса, который позволяет респонденту выбрать один выбор из списка радиопроизводительных кнопок или дополнительное поле «Другое».
add Page Break Item() Page Break Item Добавляет новый элемент макета, который отмечает начало страницы.
add Paragraph Text Item() Paragraph Text Item Добавляет новый элемент вопроса, который позволяет респонденту ввести блок текста.
add Published Reader(emailAddress) Form Добавляет данного пользователя в список респондентов для Form .
add Published Reader(user) Form Добавляет данного пользователя в список респондентов для Form .
add Published Readers(emailAddresses) Form Добавляет заданный массив пользователей в список респондентов для Form .
add Rating Item() Rating Item Добавляет новый элемент вопроса, который позволяет респонденту дать рейтинг.
add Scale Item() Scale Item Добавляет новый элемент вопроса, который позволяет респонденту выбрать одну опцию из нумерованной последовательности радиопроизводительных кнопок.
add Section Header Item() Section Header Item Добавляет новый элемент макета, который визуально указывает на начало раздела.
add Text Item() Text Item Добавляет новый элемент вопроса, который позволяет респонденту ввести одну строку текста.
add Time Item() Time Item Добавляет новый элемент вопроса, который позволяет респонденту указать время суток.
add Video Item() Video Item Добавляет новый элемент макета, который отображает видео.
can Edit Response() Boolean Определяет, отображает ли форма ссылку для редактирования ответа после его отправки.
collects Email() Boolean Определяет, собирает ли форма адреса электронной почты респондентов.
create Response() Form Response Создает новый ответ на форму.
delete All Responses() Form Удаляет все представленные ответы из магазина ответов формы.
delete Item(index) void Удаляет элемент по данному индексу среди всех элементов в форме.
delete Item(item) void Удаляет заданный элемент.
delete Response(responseId) Form Удаляет один ответ из магазина ответов формы.
get Confirmation Message() String Получает подтверждение формы.
get Custom Closed Form Message() String Получает пользовательское сообщение, которое отображается, если форма не принимает ответы, или пустую строку, если не установлено пользовательское сообщение.
get Description() String Получает описание формы.
get Destination Id() String Получает идентификатор места назначения ответа формы.
get Destination Type() Destination Type Получает тип места назначения ответа формы.
get Edit Url() String Получает URL, который можно использовать для доступа к режиму редактирования формы.
get Editors() User[] Получает список редакторов для этой Form .
get Id() String Получает идентификатор формы.
get Item By Id(id) Item Получает элемент с данным идентификатором.
get Items() Item[] Получает массив всех предметов в форме.
get Items(itemType) Item[] Получает массив всех предметов данного типа.
get Published Readers() User[] Получает список респондентов для этой Form .
get Published Url() String Получает URL, который можно использовать для реагирования на форму.
get Response(responseId) Form Response Получает один ответ формы на основе его идентификатора ответа.
get Responses() Form Response[] Получает множество ответов формы.
get Responses(timestamp) Form Response[] Получил массив всех ответов формы после данной даты и времени.
get Shuffle Questions() Boolean Определяет, рандомизируется ли порядок вопросов на каждой странице формы.
get Summary Url() String Получает URL, который может быть использован для просмотра сводки ответов формы.
get Title() String Получает название формы.
has Limit One Response Per User() Boolean Определяет, разрешает ли форма только один ответ на одного респондента.
has Progress Bar() Boolean Определяет, отображает ли форма панель прогресса.
has Respond Again Link() Boolean Определяет, отображает ли форма ссылку для отправки другого ответа после того, как ответчик заполнит форму.
is Accepting Responses() Boolean Определяет, принимает ли форма в настоящее время ответы.
is Published() Boolean Определяет, опубликована ли форма.
is Publishing Summary() Boolean Определяет, отображает ли форма ссылку для просмотра сводки ответов после того, как респондент заполнит форму.
is Quiz() Boolean Определяет, является ли форма викториной.
move Item(from, to) Item Перемещает элемент по данному индексу среди всех элементов в форме в другой указанный индекс.
move Item(item, toIndex) Item Перемещает заданный элемент к данному индексу среди всех элементов в форме.
remove Destination() Form Отсутствует форму из его текущего направления ответа.
remove Editor(emailAddress) Form Удаляет данного пользователя из списка редакторов для Form .
remove Editor(user) Form Удаляет данного пользователя из списка редакторов для Form .
remove Published Reader(emailAddress) Form Удаляет данного пользователя из списка респондентов для Form .
remove Published Reader(user) Form Удаляет данного пользователя из списка респондентов для Form .
set Accepting Responses(enabled) Form Устанавливает, принимает ли форма в настоящее время ответы.
set Allow Response Edits(enabled) Form Устанавливает, отображает ли форма ссылку для редактирования ответа после его отправки.
set Collect Email(collect) Form Устанавливает, собирает ли форма адреса электронной почты респондентов.
set Confirmation Message(message) Form Устанавливает подтверждение формы.
set Custom Closed Form Message(message) Form Устанавливает сообщение для отображения, если форма не принимает ответы.
set Description(description) Form Устанавливает описание формы.
set Destination(type, id) Form Устанавливает пункт назначения, где сохранены ответы формы.
set Is Quiz(enabled) Form Устанавливает, является ли форма викториной.
set Limit One Response Per User(enabled) Form Устанавливает, разрешает ли форма только один ответ на одного респондента.
set Progress Bar(enabled) Form Устанавливает, есть ли форма панели прогресса.
set Published(enabled) Form Устанавливает, опубликована ли форма.
set Publishing Summary(enabled) Form Устанавливает, отображает ли форма ссылку для просмотра сводки ответов после того, как респондент подает форму.
set Show Link To Respond Again(enabled) Form Устанавливает, отображает ли форма ссылку, чтобы отправить другой ответ после того, как ответчик заполнит форму.
set Shuffle Questions(shuffle) Form Устанавливает, является ли порядок вопросов на каждой странице формы рандомизирован.
set Title(title) Form Устанавливает название формы.
shorten Form Url(url) String Преобразует длинный URL для формы в короткий URL.
submit Grades(responses) Form Представляет оценки для данных форм -реагирования.
supports Advanced Responder Permissions() Boolean Определяет, поддерживает ли форма публикация.

Подробная документация

add Checkbox Grid Item()

Добавляет новый элемент вопроса, представленный в виде сетки столбцов и строк, который позволяет респонденту выбрать несколько вариантов на строку из последовательности флажков.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a checkbox grid item.
const item = form.addCheckboxGridItem();

item.setTitle('Where did you celebrate New Year\'s?');

// Sets the grid's rows and columns.
item.setRows(['New York', 'San Francisco', 'London']).setColumns([
  '2014', '2015', '2016', '2017'
]);

Возвращаться

Checkbox Grid Item - недавно созданный элемент.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Checkbox Item()

Добавляет новый элемент вопроса, который позволяет респонденту выбрать один или несколько флажков, а также дополнительное поле «Другое».

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a checkbox item.
const item = form.addCheckboxItem();

// Sets the title of the checkbox item to 'Do you prefer cats or dogs?'
item.setTitle('Do you prefer cats or dogs?');

// Sets the choices.
item.setChoiceValues(['Cats', 'Dogs']);

Возвращаться

Checkbox Item - недавно созданный элемент.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Date Item()

Добавляет новый элемент вопроса, который позволяет респонденту указать дату.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a date item.
const item = form.addDateItem();

// Sets the title to 'When were you born?'
item.setTitle('When were you born?');

// Sets the description for the date item.
item.setHelpText('Some helper text.');

Возвращаться

Date Item - недавно созданный элемент.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Date Time Item()

Добавляет новый элемент вопроса, который позволяет респонденту указать дату и время.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a question with date and time inputs.
const item = form.addDateTimeItem();

// Sets the title to 'When were you born?'
item.setTitle('When were you born?');

// Sets the question as required.
item.setRequired(true);

Возвращаться

Date Time Item - недавно созданный элемент.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Duration Item()

Добавляет новый элемент вопроса, который позволяет респонденту указать время.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a question with a duration input.
const item = form.addDurationItem();

// Sets the title to 'How long can you hold your breath?'
item.setTitle('How long can you hold your breath?');

// Sets the question as required.
item.setRequired(true);

Возвращаться

Duration Item - недавно созданный элемент.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Editor(emailAddress)

Добавляет данного пользователя в список редакторов для Form . Если пользователь уже был в списке зрителей или респондентов, этот метод продвигает пользователя из списка.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Adds editor to the form.
// TODO(developer): replace the emailAddress.
form.addEditor('editor@uni.edu');

Параметры

Имя Тип Описание
email Address String Адрес электронной почты пользователя для добавления.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Editor(user)

Добавляет данного пользователя в список редакторов для Form . Если пользователь уже был в списке зрителей или респондентов, этот метод продвигает пользователя из списка.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const oldForm = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Gets the editors from the old form.
const users = oldForm.getEditors();

// Creates a new form.
const newForm = FormApp.create('New form');

// Adds the editors to a new form.
users.forEach(user => newForm.addEditor(user));

Параметры

Имя Тип Описание
user User Представление пользователя для добавления.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Editors(emailAddresses)

Добавляет заданный массив пользователей в список редакторов для Form . Если кто -либо из пользователей уже был в списке зрителей, этот метод продвигает их из списка зрителей.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Adds editors to the form.
// TODO(developer): replace the emailAddress.
form.addPublishedReaders(['editor1@uni.edu', 'editor2@uni.edu']);

Параметры

Имя Тип Описание
email Addresses String[] Множество адресов электронной почты пользователей для добавления.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Grid Item()

Добавляет новый элемент вопроса, представленный в виде сетки столбцов и строк, который позволяет респонденту выбрать один выбор на строку из последовательности радиопроизводительных кнопок.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a multiple choice grid.
const item = form.addGridItem();

// Sets the title to 'Rate your interests.'
item.setTitle('Rate your interests');

// Sets the grid's rows and columns.
item.setRows(['Cars', 'Computers', 'Celebrities']).setColumns([
  'Boring', 'So-so', 'Interesting'
]);

Возвращаться

Grid Item - недавно созданный элемент.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Image Item()

Добавляет новый элемент макета, который отображает изображение.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds an image item.
const item = form.addImageItem();

// Gets the Google icon to use as the image.
const img = UrlFetchApp.fetch(
    'https://fonts.gstatic.com/s/i/productlogos/googleg/v6/web-24dp/logo_googleg_color_1x_web_24dp.png',
);

// Sets the image, title, and description for the item.
item.setTitle('Google icon').setHelpText('Google icon').setImage(img);

Возвращаться

Image Item - недавно созданный элемент.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add List Item()

Добавляет новый элемент вопроса, который позволяет респонденту выбрать один выбор из раскрывающегося списка.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a dropdown list to the form.
const item = form.addListItem();

// Sets the title to 'Do you prefer cats or dogs?'
item.setTitle('Do you prefer cats or dogs?');

// Sets the description to 'This is description text...'
item.setHelpText('This is description text...');

// Creates and adds choices to the dropdown list.
item.setChoices([item.createChoice('dog'), item.createChoice('cat')]);

Возвращаться

List Item - недавно созданный элемент.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Multiple Choice Item()

Добавляет новый элемент вопроса, который позволяет респонденту выбрать один выбор из списка радиопроизводительных кнопок или дополнительное поле «Другое».

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a multiple choice item to the form.
const item = form.addMultipleChoiceItem();

// Sets the title.
item.setTitle('What is your favorite ice cream flavor?');

// Creates some choice items.
const vanilla = item.createChoice('vanilla');
const chocolate = item.createChoice('chocolate');
const strawberry = item.createChoice('strawberry');

// Sets the choices.
item.setChoices([vanilla, chocolate, strawberry]);

Возвращаться

Multiple Choice Item - новый элемент.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Page Break Item()

Добавляет новый элемент макета, который отмечает начало страницы.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds page break items to create a second and third page for the form.
const pageTwo = form.addPageBreakItem();
const pageThree = form.addPageBreakItem();

// Sets the titles for the pages.
pageTwo.setTitle('Page two');
pageThree.setTitle('Page three');

// Upon completion of the first page, sets the form to navigate to the third
// page.
pageTwo.setGoToPage(pageThree);

// Upon completion of the second page, sets the form to navigate back to the
// first page.
pageThree.setGoToPage(FormApp.PageNavigationType.RESTART);

Возвращаться

Page Break Item - недавно созданный элемент.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Paragraph Text Item()

Добавляет новый элемент вопроса, который позволяет респонденту ввести блок текста.

// Opens the form by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds the paragraph text item.
const item = form.addParagraphTextItem();

// Sets the title to 'What is your address?'
item.setTitle('What is your address?');

Возвращаться

Paragraph Text Item - недавно созданный элемент.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Published Reader(emailAddress)

Добавляет данного пользователя в список респондентов для Form . Если пользователь уже был в списке редакторов или зрителей, этот метод не имеет эффекта.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Adds responder to the form.
// TODO(developer): replace the emailAddress.
form.addPublishedReader('responder@uni.edu');

Параметры

Имя Тип Описание
email Address String Адрес электронной почты пользователя для добавления.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Published Reader(user)

Добавляет данного пользователя в список респондентов для Form . Если пользователь уже был в списке редакторов или зрителей, этот метод не имеет эффекта.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const oldForm = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Gets the responders from the old form.
const users = oldForm.getPublishedReaders();

// Creates a new form.
const newForm = FormApp.create('New form');

// Adds the responders to a new form.
users.forEach(user => newForm.addPublishedReader(user));

Параметры

Имя Тип Описание
user User Представление пользователя для добавления.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Published Readers(emailAddresses)

Добавляет заданный массив пользователей в список респондентов для Form . Если пользователь уже был в списке редакторов или зрителей, этот метод не имеет эффекта.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Adds responders to the form.
// TODO(developer): replace the emailAddress.
form.addPublishedReaders(['responder1@uni.edu', 'responder2@uni.edu']);

Параметры

Имя Тип Описание
email Addresses String[] Множество адресов электронной почты пользователей для добавления.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Rating Item()

Добавляет новый элемент вопроса, который позволяет респонденту дать рейтинг.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds the rating item.
const item = form.addRatingItem();

Возвращаться

Rating Item - недавно созданный элемент.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Scale Item()

Добавляет новый элемент вопроса, который позволяет респонденту выбрать одну опцию из нумерованной последовательности радиопроизводительных кнопок.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds the scale item.
const item = form.addScaleItem();

// Sets the title of the scale item to 'Choose a number.'
item.setTitle('Choose a number');

// Sets the scale to 1-5.
item.setBounds(1, 5);

// Sets the label for the lower and upper bounds.
item.setLabels('Lowest', 'Highest');

Возвращаться

Scale Item - недавно созданный элемент.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Section Header Item()

Добавляет новый элемент макета, который визуально указывает на начало раздела.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds the section heading item.
const item = form.addSectionHeaderItem();

// Sets the title to 'Title of new section.'
item.setTitle('Title of new section');

// Sets the description.
item.setHelpText('Description of new section');

Возвращаться

Section Header Item - недавно созданный элемент.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Text Item()

Добавляет новый элемент вопроса, который позволяет респонденту ввести одну строку текста.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a single-line text item.
const item = form.addTextItem();

// Sets the title to 'What is your name?'
item.setTitle('What is your name?');

Возвращаться

Text Item - недавно созданный элемент.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Time Item()

Добавляет новый элемент вопроса, который позволяет респонденту указать время суток.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a question with a time input.
const item = form.addTimeItem();

// Sets the title to 'What time do you usually wake up in the morning?'
item.setTitle('What time do you usually wake up in the morning?');

Возвращаться

Time Item - недавно созданный элемент.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Video Item()

Добавляет новый элемент макета, который отображает видео.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a video item.
const item = form.addVideoItem();

// Sets the title, description, and video.
item.setTitle('YouTube video')
    .setHelpText('Send content automatically via Google Sheets and Apps Script')
    .setVideoUrl('https://youtu.be/xxgQr-jSu9o');

// Sets the alignment to the center.
item.setAlignment(FormApp.Alignment.CENTER);

Возвращаться

Video Item - недавно созданный элемент.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

can Edit Response()

Определяет, отображает ли форма ссылку для редактирования ответа после его отправки.

Независимо от этого настройки, метод Form Response.getEditResponseUrl() позволяет автору сценария, который имеет доступ к форме для генерации URL, который можно использовать для редактирования ответа.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Checks if the form displays a link to edit a response after submitting it.
// The default is false. To let people edit their responses, use
// form.setAllowResponseEdits(true).
const edit = form.canEditResponse();

// If the form doesn't let people edit responses, logs false to the console.
console.log(edit);

Возвращаться

Boolean - true , если форма отображает ссылку «редактировать ваш ответ»; false если это не так.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

collects Email()

Определяет, собирает ли форма адреса электронной почты респондентов.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to not collect respondents' email addresses.
form.setCollectEmail(false);

// Checks whether the form collects respondents' email addresses and logs it to
// the console.
const bool = form.collectsEmail();

console.log(bool);

Возвращаться

Boolean - true , если форма собирает адреса электронной почты; false если это не так.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

create Response()

Создает новый ответ на форму. Чтобы ответить на элемент вопроса, создайте Item Response из элемента, затем прикрепите его к ответу на эту форму, вызывая Form Response.withItemResponse(response) . Чтобы сохранить собственный ответ, вызовой Form Response.submit() .

Возвращаться

Form Response - недавно созданный ответ формы.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

delete All Responses()

Удаляет все представленные ответы из магазина ответов формы. Этот метод не удаляет копии ответов, хранящихся в направлении внешнего ответа (например, электронной таблицы), но очищает краткое представление формы.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

delete Item(index)

Удаляет элемент по данному индексу среди всех элементов в форме. Бросает исключение сценариев, если в данном индексе нет элемента.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets all the items from the form.
const items = form.getItems();

// Finds the index of a paragraph text item and deletes it by the item's index.
const index = items.findIndex(
    (item) => item.getType() === FormApp.ItemType.PARAGRAPH_TEXT,
);
if (index !== -1) {
  form.deleteItem(index);
}

Параметры

Имя Тип Описание
index Integer Индекс элемента среди всех элементов в форме.

Броски

Error - если в данном индексе нет элемента

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

delete Item(item)

Удаляет заданный элемент. Бросает исключение сценариев, если элемент уже был удален.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets all of the items from the form.
const items = form.getItems();

// Finds a paragraph text item and deletes it.
const item = items.find(
    (item) => item.getType() === FormApp.ItemType.PARAGRAPH_TEXT,
);
if (item) {
  form.deleteItem(item);
}

Параметры

Имя Тип Описание
item Item Предмет, который будет удален.

Броски

Error - если элемент не существует в форме

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

delete Response(responseId)

Удаляет один ответ из магазина ответов формы. Этот метод не удаляет копии ответов, хранящихся в направлении внешнего ответа (например, электронной таблицы), но удаляет ответ из краткого представления формы. Идентификатор ответа может быть извлечен с помощью Form Response.getId() .

Параметры

Имя Тип Описание
response Id String Идентификатор ответа формы на удаление.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Confirmation Message()

Получает подтверждение формы.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the confirmation message to display after someone submits the form.
form.setConfirmationMessage('You successfully submitted the form.');

// Gets the confirmation message and logs it to the console.
const message = form.getConfirmationMessage();

console.log(message);

Возвращаться

String - подтверждающее сообщение формы.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Custom Closed Form Message()

Получает пользовательское сообщение, которое отображается, если форма не принимает ответы, или пустую строку, если не установлено пользовательское сообщение.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets a custom closed form message to display to the user when the form
// no longer accepts responses.
form.setCustomClosedFormMessage('The form is no longer accepting responses.');

// Gets the custom message set for the form and logs it to the console.
const message = form.getCustomClosedFormMessage();

console.log(message);

Возвращаться

String - пользовательское сообщение для отображения, если форма не принимает ответы, или пустая строка, если не установлено пользовательское сообщение.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Description()

Получает описание формы.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form description.
form.setDescription('This is the form description.');

// Gets the form description and logs it to the console.
const description = form.getDescription();

console.log(description);

Возвращаться

String - описание формы.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Destination Id()

Получает идентификатор места назначения ответа формы.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Creates a spreadsheet to use as the response destination.
const ss = SpreadsheetApp.create('Test_Spreadsheet');

// Updates the form's response destination.
form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());

// Gets the ID of the form's response destination and logs it to the console.
const destinationId = form.getDestinationId();

console.log(destinationId);

Возвращаться

String - идентификатор места назначения ответа формы.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Destination Type()

Получает тип места назначения ответа формы.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc1234556/edit',
);

// Gets the type of the form's response destination and logs it to the console.
const destinationType = form.getDestinationType().name();

console.log(destinationType);

Возвращаться

Destination Type - тип места назначения ответа формы.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Edit Url()

Получает URL, который можно использовать для доступа к режиму редактирования формы.

// Opens the form by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the URL that accesses the form's edit mode and logs it to the console.
const url = form.getEditUrl();

console.log(url);

Возвращаться

String - URL для редактирования формы.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Editors()

Получает список редакторов для этой Form .

Возвращаться

User[] - массив пользователей с разрешения редактирования.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Id()

Получает идентификатор формы.

// Opens the form by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the ID of the form and logs it to the console.
const id = form.getId();

console.log(id);

Возвращаться

String - идентификатор формы.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Item By Id(id)

Получает элемент с данным идентификатором. Возвращает null если идентификатор не соответствует элементу в форме.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the ID of the first item on the form.
const itemId = form.getItems()[0].getId();

// Gets the item from the ID.
const item = form.getItemById(itemId);

// Gets the name of the item type and logs it to the console.
const type = item.getType().name();

console.log(type);

Параметры

Имя Тип Описание
id Integer Идентификатор элемента.

Возвращаться

Item - элемент с данным идентификатором или null если элемент не существует в форме.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Items()

Получает массив всех предметов в форме.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the list of items in the form.
const items = form.getItems();

// Gets the type for each item and logs them to the console.
const types = items.map((item) => item.getType().name());

console.log(types);

Возвращаться

Item[] - массив всех элементов в форме.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Items(itemType)

Получает массив всех предметов данного типа.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets a list of all checkbox items on the form.
const items = form.getItems(FormApp.ItemType.CHECKBOX);

// Gets the title of each checkbox item and logs them to the console.
const checkboxItemsTitle = items.map(
    (item) => item.asCheckboxItem().getTitle(),
);
console.log(checkboxItemsTitle);

Параметры

Имя Тип Описание
item Type Item Type Тип предметов для извлечения.

Возвращаться

Item[] - массив всех элементов такого типа.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Published Readers()

Получает список респондентов для этой Form .

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Gets the responders for the form.
const users = form.getPublishedReaders();
users.forEach(user => console.log(user.getEmail()));

Возвращаться

User[] - массив пользователей с разрешением респондента.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Published Url()

Получает URL, который можно использовать для реагирования на форму.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the URL to respond to the form and logs it to the console.
const url = form.getPublishedUrl();
console.log(url);

Возвращаться

String - URL -адрес для ответа на форму.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Response(responseId)

Получает один ответ формы на основе его идентификатора ответа. Идентификаторы ответа могут быть извлечены из Form Response.getId() .

Параметры

Имя Тип Описание
response Id String Идентификатор для ответа формы.

Возвращаться

Form Response - ответ формы.

Броски

Error - если ответа не существует

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Responses()

Получает множество ответов формы.

Возвращаться

Form Response[] - массив всех ответов формы.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Responses(timestamp)

Получил массив всех ответов формы после данной даты и времени.

Параметры

Имя Тип Описание
timestamp Date Самая ранняя дата и время, для которых ответы формы должны быть возвращены.

Возвращаться

Form Response[] - Список ответов формы.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Shuffle Questions()

Определяет, рандомизируется ли порядок вопросов на каждой странице формы.

Возвращаться

Boolean - true если порядок вопросов на каждой странице формы рандомизирован; false если нет.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Summary Url()

Получает URL, который может быть использован для просмотра сводки ответов формы. Если не set Publishing Summary(enabled) не установлено в true , только пользователи с редактированием в форму могут получить доступ к URL.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// Opens the form by its URL.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the URL to view a summary of the form's responses and logs it to the
// console.
const url = form.getSummaryUrl();
console.log(url);

Возвращаться

String - URL для просмотра краткого изложения ответов.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Title()

Получает название формы.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the title of the form to 'For_Testing.'
form.setTitle('For_Testing');

// Gets the title of the form and logs it to the console.
const title = form.getTitle();
console.log(title);

Возвращаться

String - название формы.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

has Limit One Response Per User()

Определяет, разрешает ли форма только один ответ на одного респондента. Если значение true , сценарий вообще не может представить ответы формы.

Возвращаться

Boolean - true , если форма допускает только один ответ на одного респондента; false если нет.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

has Progress Bar()

Определяет, отображает ли форма панель прогресса.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// Opens the form by its URL.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Displays the progress bar on the form.
form.setProgressBar(true);

// Checks if the form displays a progress bar and logs it to the console.
console.log(form.hasProgressBar());

Возвращаться

Boolean - true , если форма отображает панель прогресса; false если это не так.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

Определяет, отображает ли форма ссылку для отправки другого ответа после того, как ответчик заполнит форму.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to display a link to submit another
// response after someone submits the form.
form.setShowLinkToRespondAgain(true);

// Checks if the form displays a 'Submit another response' link and logs it to
// the console.
console.log(form.hasRespondAgainLink());

Возвращаться

Boolean - true , если в форме отображается ссылка «отправить другой ответ»; false если это не так.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

is Accepting Responses()

Определяет, принимает ли форма в настоящее время ответы. Это перезаписывается, когда изменение состояния публикации формы.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to accept responses.
form.setAcceptingResponses(true);

// Checks if the form is accepting responses or not and logs it to the console.
const accepting = form.isAcceptingResponses();
console.log(accepting);

Возвращаться

Boolean - true если форма принимает ответы; false если это не так.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

is Published()

Определяет, опубликована ли форма.

Эта функция доступна только для форм, которые поддерживают публикацию. Используйте supports Advanced Responder Permissions() чтобы проверить, поддерживает ли форма публикация.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Checks whether the form is published or not and logs it to the console.
console.log(form.isPublished());

Возвращаться

Boolean - true если форма опубликована; false если это не так.

Броски

Error - если вызов на неподдерживаемых формах.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

is Publishing Summary()

Определяет, отображает ли форма ссылку для просмотра сводки ответов после того, как респондент заполнит форму.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to display a link to a summary of
// the responses after someone submits the form.
form.setPublishingSummary(true);

// Checks if the form displays a "See previous responses" link and logs it to
// the console.
const publishingLink = form.isPublishingSummary();
console.log(publishingLink);

Возвращаться

Boolean - true , если форма отображает ссылку «См. Предыдущие ответы»; false если это не так.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

is Quiz()

Определяет, является ли форма викториной.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form as a quiz.
form.setIsQuiz(true);

// Checks if the form is a quiz or not and logs it to the console.
console.log(form.isQuiz());

Возвращаться

Boolean - true если форма принимает ответы; false если это не так.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

move Item(from, to)

Перемещает элемент по данному индексу среди всех элементов в форме в другой указанный индекс. Отбрасывает исключение сценариев, если индекс to индекса выходит за пределы.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Moves the first item to be the last item.
form.moveItem(0, form.getItems().length - 1);

Параметры

Имя Тип Описание
from Integer Текущий индекс элемента среди всех элементов в форме.
to Integer Новый индекс для элемента среди всех элементов в форме.

Возвращаться

Item - предмет, который был перемещен.

Броски

Error - если какой -либо индекс выходит за пределы.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

move Item(item, toIndex)

Перемещает заданный элемент к данному индексу среди всех элементов в форме. Бросает исключение сценариев, если заданный индекс вышел за пределы.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the first item.
const item = form.getItems()[0];

// Moves the item to be the last item.
form.moveItem(item, form.getItems().length - 1);

Параметры

Имя Тип Описание
item Item Предмет для перемещения.
to Index Integer Новый индекс для элемента среди всех элементов в форме.

Возвращаться

Item - предмет, который был перемещен.

Броски

Error - если индекс выходит за пределы.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

remove Destination()

Отсутствует форму из его текущего направления ответа. Неопределенный бывший пункт назначения все еще сохраняет копию всех предыдущих ответов. Все формы, в том числе те, которые не имеют набора назначения явно, сохраняют копию ответов в магазине ответов формы . Если в настоящее время форма не имеет места назначения ответа, этот метод не имеет никакого эффекта.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Opens a spreadsheet to use for the response destination.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Updates the form's response destination to the spreadsheet.
form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());

// Unlinks the form from the spreadsheet.
form.removeDestination();

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

remove Editor(emailAddress)

Удаляет данного пользователя из списка редакторов для Form . Этот метод не блокирует пользователей от доступа к Form , если они принадлежат к классу пользователей, которые имеют общий доступ, например, если Form передается со всем доменом пользователя, или если Form находится в общем диске, к которому пользователь может получить доступ.

Для файлов диска это также удаляет пользователя из списка зрителей и респондентов.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Removes the editor from the form.
// TODO(developer): replace the emailAddress.
form.removeEditor('editor@uni.edu');

Параметры

Имя Тип Описание
email Address String Адрес электронной почты пользователя для удаления.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

remove Editor(user)

Удаляет данного пользователя из списка редакторов для Form . Этот метод не блокирует пользователей от доступа к Form , если они принадлежат к классу пользователей, которые имеют общий доступ, например, если Form передается со всем доменом пользователя, или если Form находится в общем диске, к которому пользователь может получить доступ.

Для файлов диска это также удаляет пользователя из списка зрителей.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const form1 = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Gets the editors from the form.
const users = form1.getEditors();

// Opens another form.
// TODO(developer): Replace the URL with your own.
const form2 = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Removes editors from the form.
users.forEach(user => form2.removeEditor(user));

Параметры

Имя Тип Описание
user User Представление пользователя для удаления.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

remove Published Reader(emailAddress)

Удаляет данного пользователя из списка респондентов для Form . Этот метод не блокирует пользователей от доступа к Form , если они принадлежат к классу пользователей, которые имеют общий доступ, например, если Form передается со всем доменом пользователя, или если Form находится в общем диске, к которому пользователь может получить доступ.

Для файлов диска это также удаляет пользователя из списка зрителей и редакторов.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Removes the responders from the form.
// TODO(developer): replace the emailAddress.
form.removePublishedReader('responder1@uni.edu');

Параметры

Имя Тип Описание
email Address String Адрес электронной почты пользователя для удаления.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

remove Published Reader(user)

Удаляет данного пользователя из списка респондентов для Form . Этот метод не блокирует пользователей от доступа к Form , если они принадлежат к классу пользователей, которые имеют общий доступ, например, если Form передается со всем доменом пользователя, или если Form находится в общем диске, к которому пользователь может получить доступ.

Для файлов диска это также удаляет пользователя из списка зрителей и редакторов.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const form1 = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Gets the responders from the form.
const users = form1.getPublishedReaders();

// Opens another form.
// TODO(developer): Replace the URL with your own.
const form2 = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Removes responders from the form.
users.forEach(user => form2.removePublishedReader(user));

Параметры

Имя Тип Описание
user User Представление пользователя для удаления.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Accepting Responses(enabled)

Устанавливает, принимает ли форма в настоящее время ответы. По умолчанию для новых форм true . Государство перезаписано, когда изменение состояния публикации формы.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to accept responses.
form.setAcceptingResponses(true);

// Checks whether the form is accepting responses or not and logs it to the
// console.
console.log(form.isAcceptingResponses());

Параметры

Имя Тип Описание
enabled Boolean true если форма должна принимать ответы; false если это не должно.

Возвращаться

Form - эта Form , для цепочки.

Броски

Error - если включена в неопубликованной форме.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Allow Response Edits(enabled)

Устанавливает, отображает ли форма ссылку для редактирования ответа после его отправки. По умолчанию для новых форм false .

Независимо от этого настройки, метод Form Response.getEditResponseUrl() позволяет автору сценария, который имеет разрешение на редактирование на форму для создания URL, который можно использовать для редактирования ответа.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Shows "Edit your response" link after someone submits the form.
form.setAllowResponseEdits(true);

// Checks whether the option to edit the form after a user submits it is set to
// true or not and logs it to the console.
console.log(form.canEditResponse());

Параметры

Имя Тип Описание
enabled Boolean true , если форма должна отображать ссылку «Изменить ваш ответ»; false если нет.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Collect Email(collect)

Устанавливает, собирает ли форма адреса электронной почты респондентов. По умолчанию для новых форм false .

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to collect respondents' email addresses.
form.setCollectEmail(true);

// Checks whether the value is set to true or false and logs it to the console.
const collect = form.collectsEmail();
console.log(collect);

Параметры

Имя Тип Описание
collect Boolean true , если форма должна собирать адреса электронной почты; false если это не так.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Confirmation Message(message)

Устанавливает подтверждение формы.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets a custom confirmation message to display after someone submits the form.
form.setConfirmationMessage('Your form has been successfully submitted.');

// Gets the confirmation message set for the form and logs it to the console.
const message = form.getConfirmationMessage();
console.log(message);

Параметры

Имя Тип Описание
message String Новое подтверждающее сообщение формы.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Custom Closed Form Message(message)

Устанавливает сообщение для отображения, если форма не принимает ответы. Если не установлено сообщение, в форме используется сообщение по умолчанию.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to not accept responses.
form.setAcceptingResponses(false);

// Sets a custom closed form message to display to the user.
form.setCustomClosedFormMessage('The form is no longer accepting responses.');

// Gets the custom message set for the form and logs it to the console.
const message = form.getCustomClosedFormMessage();
console.log(message);

Параметры

Имя Тип Описание
message String Сообщение для отображения, если форма не принимает ответы.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Description(description)

Устанавливает описание формы.

Параметры

Имя Тип Описание
description String Новое описание формы.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Destination(type, id)

Устанавливает пункт назначения, где сохранены ответы формы. Все формы, в том числе те, которые не имеют набора назначения явно, сохраняют копию ответов в магазине ответов формы .

Параметры

Имя Тип Описание
type Destination Type Тип места назначения ответа формы.
id String Идентификатор места назначения ответа формы.

Возвращаться

Form - эта Form , для цепочки.

Броски

Error - если данный идентификатор назначения недействителен

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Is Quiz(enabled)

Устанавливает, является ли форма викториной. По умолчанию для новых форм false .

Расчетные вопросы разрешены только в тестах, поэтому устанавливает это на false причины, все варианты оценки будут удалены из всех вопросов.

Настройки викторины доступны только в пользовательском интерфейсе новых форм; Создание формы викторина выбирает форму в использование нового пользовательского интерфейса.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Makes the form a quiz.
form.setIsQuiz(true);

// Checks whether the form is a quiz or not and logs it to the console.
console.log(form.isQuiz());

Параметры

Имя Тип Описание
enabled Boolean true , если функции викторины должны быть включены для формы; false если нет.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Limit One Response Per User(enabled)

Устанавливает, разрешает ли форма только один ответ на одного респондента. По умолчанию для новых форм false . Если значение установлено в true , скрипт вообще не может представить ответы формы.

Параметры

Имя Тип Описание
enabled Boolean true если форма должна разрешить только один ответ на одного респондента; false если нет.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Progress Bar(enabled)

Устанавливает, есть ли форма панели прогресса. По умолчанию для новых форм false .

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Displays the progress bar on the form.
form.setProgressBar(true);

// Checks whether the form has a progress bar and logs it to the console.
console.log(form.hasProgressBar());

Параметры

Имя Тип Описание
enabled Boolean true , если форма отображает панель прогресса; false если это не так.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Published(enabled)

Устанавливает, опубликована ли форма. По умолчанию для новых форм true .

Эта функция доступна только для форм, которые поддерживают публикацию. Используйте supports Advanced Responder Permissions() чтобы проверить, поддерживает ли форма публикация.

Форма должна быть опубликована, чтобы она была доступна для респондентов. Этот метод заменяет вызовы для set Accepting Responses(enabled) .

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Publishes the form before sharing it.
form.setPublished(true);

// Checks whether the form is published or not and logs it to the console.
console.log(form.isPublished());

Параметры

Имя Тип Описание
enabled Boolean true , если форма должна быть опубликована, false если нет.

Возвращаться

Form - эта Form , для цепочки.

Броски

Error - если вызов на неподдерживаемых формах.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Publishing Summary(enabled)

Устанавливает, отображает ли форма ссылку для просмотра сводки ответов после того, как респондент подает форму. По умолчанию для новых форм false .

Параметры

Имя Тип Описание
enabled Boolean true , если форма должна отображать ссылку «См. Предыдущие ответы»; false если нет.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Show Link To Respond Again(enabled)

Устанавливает, отображает ли форма ссылку, чтобы отправить другой ответ после того, как ответчик заполнит форму. По умолчанию для новых форм true .

Параметры

Имя Тип Описание
enabled Boolean true , если форма должна отображать ссылку «Отправить другой ответ»; false если нет.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Shuffle Questions(shuffle)

Устанавливает, является ли порядок вопросов на каждой странице формы рандомизирован.

Параметры

Имя Тип Описание
shuffle Boolean true , если порядок вопросов на каждой странице формы должен быть рандомизирован; false если нет.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Title(title)

Устанавливает название формы.

Параметры

Имя Тип Описание
title String Новое название формы.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

shorten Form Url(url)

Преобразует длинный URL для формы в короткий URL. Бросает исключение, если длинный URL не принадлежит форм Google.

Параметры

Имя Тип Описание
url String URL укоротить.

Возвращаться

String - URL в форме http://goo.gl/forms/1234 .

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

submit Grades(responses)

Представляет оценки для данных форм -реагирования.

Если ваш код включает в себя триггер on Form Submit , вызовы submit Grades() запускают условие on Form Submit и вызывает бесконечный цикл. Чтобы предотвратить бесконечный цикл, добавьте код, который проверяет, существуют ли оценки уже перед вызовом submit Grades() .

Параметры

Имя Тип Описание
responses Form Response[] Массив всех ответов формы.

Возвращаться

Form - эта Form , для цепочки.

Авторизация

Сценарии, которые используют этот метод, требуют авторизации с одним или несколькими из следующих областей :

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

supports Advanced Responder Permissions()

Determines whether the form supports publishing. This method is used to determine whether the set Published(enabled) and is Published() methods, and responder permissions, are available.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Checks whether the form supports publishing or not and logs it to the
// console.
console.log(form.supportsAdvancedResponderPermissions());

Возвращаться

Booleantrue if the form supports publishing; false if it doesn't.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

Deprecated methods


,
Форма

A form that contains overall properties and items. Properties include title, settings, and where responses are stored. Items include question items like checkboxes or radio items, while layout items refer to things like page breaks. Forms can be accessed or created from Form App .

// Open a form by ID and create a new spreadsheet.
const form = FormApp.openById('1234567890abcdefghijklmnopqrstuvwxyz');
const ss = SpreadsheetApp.create('Spreadsheet Name');

// Update form properties via chaining.
form.setTitle('Form Name')
    .setDescription('Description of form')
    .setConfirmationMessage('Thanks for responding!')
    .setAllowResponseEdits(true)
    .setAcceptingResponses(false);

// Update the form's response destination.
form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());

Методы

Метод Return type Brief description
add Checkbox Grid Item() Checkbox Grid Item Appends a new question item, presented as a grid of columns and rows, that allows the respondent to select multiple choices per row from a sequence of checkboxes.
add Checkbox Item() Checkbox Item Appends a new question item that allows the respondent to select one or more checkboxes, as well as an optional "other" field.
add Date Item() Date Item Appends a new question item that allows the respondent to indicate a date.
add Date Time Item() Date Time Item Appends a new question item that allows the respondent to indicate a date and time.
add Duration Item() Duration Item Appends a new question item that allows the respondent to indicate a length of time.
add Editor(emailAddress) Form Adds the given user to the list of editors for the Form .
add Editor(user) Form Adds the given user to the list of editors for the Form .
add Editors(emailAddresses) Form Adds the given array of users to the list of editors for the Form .
add Grid Item() Grid Item Appends a new question item, presented as a grid of columns and rows, that allows the respondent to select one choice per row from a sequence of radio buttons.
add Image Item() Image Item Appends a new layout item that displays an image.
add List Item() List Item Appends a new question item that allows the respondent to select one choice from a dropdown list.
add Multiple Choice Item() Multiple Choice Item Adds a new question item that allows the respondent to select one choice from a list of radio buttons or an optional "other" field.
add Page Break Item() Page Break Item Adds a new layout item that marks the start of a page.
add Paragraph Text Item() Paragraph Text Item Adds a new question item that allows the respondent to enter a block of text.
add Published Reader(emailAddress) Form Adds the given user to the list of responders for the Form .
add Published Reader(user) Form Adds the given user to the list of responders for the Form .
add Published Readers(emailAddresses) Form Adds the given array of users to the list of responders for the Form .
add Rating Item() Rating Item Appends a new question item that allows the respondent to give a rating.
add Scale Item() Scale Item Appends a new question item that allows the respondent to choose one option from a numbered sequence of radio buttons.
add Section Header Item() Section Header Item Appends a new layout item that visually indicates the start of a section.
add Text Item() Text Item Appends a new question item that allows the respondent to enter a single line of text.
add Time Item() Time Item Appends a new question item that allows the respondent to indicate a time of day.
add Video Item() Video Item Appends a new layout item that displays a video.
can Edit Response() Boolean Determines whether the form displays a link to edit a response after submitting it.
collects Email() Boolean Determines whether the form collects respondents' email addresses.
create Response() Form Response Creates a new response to the form.
delete All Responses() Form Deletes all submitted responses from the form's response store.
delete Item(index) void Deletes the item at a given index among all the items in the form.
delete Item(item) void Deletes the given item.
delete Response(responseId) Form Deletes a single response from the form's response store.
get Confirmation Message() String Gets the form's confirmation message.
get Custom Closed Form Message() String Gets the custom message that is displayed if the form is not accepting responses, or an empty string if no custom message is set.
get Description() String Gets the form's description.
get Destination Id() String Gets the ID of the form's response destination.
get Destination Type() Destination Type Gets the type of the form's response destination.
get Edit Url() String Gets the URL that can be used to access the form's edit mode.
get Editors() User[] Gets the list of editors for this Form .
get Id() String Gets the ID of the form.
get Item By Id(id) Item Gets the item with a given ID.
get Items() Item[] Gets an array of all items in the form.
get Items(itemType) Item[] Gets an array of all items of a given type.
get Published Readers() User[] Gets the list of responders for this Form .
get Published Url() String Gets the URL that can be used to respond to the form.
get Response(responseId) Form Response Gets a single form response based on its response ID.
get Responses() Form Response[] Gets an array of all of the form's responses.
get Responses(timestamp) Form Response[] Gets an array of all of the form's responses after a given date and time.
get Shuffle Questions() Boolean Determines whether the order of the questions on each page of the form is randomized.
get Summary Url() String Gets the URL that can be used to view a summary of the form's responses.
get Title() String Gets the form's title.
has Limit One Response Per User() Boolean Determines whether the form allows only one response per respondent.
has Progress Bar() Boolean Determines whether the form displays a progress bar.
has Respond Again Link() Boolean Determines whether the form displays a link to submit another response after a respondent completes the form.
is Accepting Responses() Boolean Determines whether the form is currently accepting responses.
is Published() Boolean Determines whether the form is published.
is Publishing Summary() Boolean Determines whether the form displays a link to view a summary of responses after a respondent completes the form.
is Quiz() Boolean Determines whether the form is a quiz.
move Item(from, to) Item Moves an item at a given index among all the items in the form to another given index.
move Item(item, toIndex) Item Moves a given item to a given index among all the items in the form.
remove Destination() Form Unlinks the form from its current response destination.
remove Editor(emailAddress) Form Removes the given user from the list of editors for the Form .
remove Editor(user) Form Removes the given user from the list of editors for the Form .
remove Published Reader(emailAddress) Form Removes the given user from the list of responders for the Form .
remove Published Reader(user) Form Removes the given user from the list of responders for the Form .
set Accepting Responses(enabled) Form Sets whether the form is currently accepting responses.
set Allow Response Edits(enabled) Form Sets whether the form displays a link to edit a response after submitting it.
set Collect Email(collect) Form Sets whether the form collects respondents' email addresses.
set Confirmation Message(message) Form Sets the form's confirmation message.
set Custom Closed Form Message(message) Form Sets the message to display if the form is not accepting responses.
set Description(description) Form Sets the form's description.
set Destination(type, id) Form Sets the destination where form responses are saved.
set Is Quiz(enabled) Form Sets whether the form is a quiz.
set Limit One Response Per User(enabled) Form Sets whether the form allows only one response per respondent.
set Progress Bar(enabled) Form Sets whether the form has a progress bar.
set Published(enabled) Form Sets whether the form is published.
set Publishing Summary(enabled) Form Sets whether the form displays a link to view a summary of responses after a respondent submits the form.
set Show Link To Respond Again(enabled) Form Sets whether the form displays a link to submit another response after a respondent completes the form.
set Shuffle Questions(shuffle) Form Sets whether the order of the questions on each page of the form is randomized.
set Title(title) Form Sets the form's title.
shorten Form Url(url) String Converts a long URL for a form to a short URL.
submit Grades(responses) Form Submits grades for the given FormResponses.
supports Advanced Responder Permissions() Boolean Determines whether the form supports publishing.

Detailed documentation

add Checkbox Grid Item()

Appends a new question item, presented as a grid of columns and rows, that allows the respondent to select multiple choices per row from a sequence of checkboxes.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a checkbox grid item.
const item = form.addCheckboxGridItem();

item.setTitle('Where did you celebrate New Year\'s?');

// Sets the grid's rows and columns.
item.setRows(['New York', 'San Francisco', 'London']).setColumns([
  '2014', '2015', '2016', '2017'
]);

Возвращаться

Checkbox Grid Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Checkbox Item()

Appends a new question item that allows the respondent to select one or more checkboxes, as well as an optional "other" field.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a checkbox item.
const item = form.addCheckboxItem();

// Sets the title of the checkbox item to 'Do you prefer cats or dogs?'
item.setTitle('Do you prefer cats or dogs?');

// Sets the choices.
item.setChoiceValues(['Cats', 'Dogs']);

Возвращаться

Checkbox Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Date Item()

Appends a new question item that allows the respondent to indicate a date.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a date item.
const item = form.addDateItem();

// Sets the title to 'When were you born?'
item.setTitle('When were you born?');

// Sets the description for the date item.
item.setHelpText('Some helper text.');

Возвращаться

Date Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Date Time Item()

Appends a new question item that allows the respondent to indicate a date and time.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a question with date and time inputs.
const item = form.addDateTimeItem();

// Sets the title to 'When were you born?'
item.setTitle('When were you born?');

// Sets the question as required.
item.setRequired(true);

Возвращаться

Date Time Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Duration Item()

Appends a new question item that allows the respondent to indicate a length of time.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a question with a duration input.
const item = form.addDurationItem();

// Sets the title to 'How long can you hold your breath?'
item.setTitle('How long can you hold your breath?');

// Sets the question as required.
item.setRequired(true);

Возвращаться

Duration Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Editor(emailAddress)

Adds the given user to the list of editors for the Form . If the user was already on the list of viewers or responders, this method promotes the user out of the list.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Adds editor to the form.
// TODO(developer): replace the emailAddress.
form.addEditor('editor@uni.edu');

Параметры

Имя Тип Описание
email Address String The email address of the user to add.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Editor(user)

Adds the given user to the list of editors for the Form . If the user was already on the list of viewers or responders, this method promotes the user out of the list.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const oldForm = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Gets the editors from the old form.
const users = oldForm.getEditors();

// Creates a new form.
const newForm = FormApp.create('New form');

// Adds the editors to a new form.
users.forEach(user => newForm.addEditor(user));

Параметры

Имя Тип Описание
user User A representation of the user to add.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Editors(emailAddresses)

Adds the given array of users to the list of editors for the Form . If any of the users were already on the list of viewers, this method promotes them out of the list of viewers.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Adds editors to the form.
// TODO(developer): replace the emailAddress.
form.addPublishedReaders(['editor1@uni.edu', 'editor2@uni.edu']);

Параметры

Имя Тип Описание
email Addresses String[] An array of email addresses of the users to add.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Grid Item()

Appends a new question item, presented as a grid of columns and rows, that allows the respondent to select one choice per row from a sequence of radio buttons.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a multiple choice grid.
const item = form.addGridItem();

// Sets the title to 'Rate your interests.'
item.setTitle('Rate your interests');

// Sets the grid's rows and columns.
item.setRows(['Cars', 'Computers', 'Celebrities']).setColumns([
  'Boring', 'So-so', 'Interesting'
]);

Возвращаться

Grid Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Image Item()

Appends a new layout item that displays an image.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds an image item.
const item = form.addImageItem();

// Gets the Google icon to use as the image.
const img = UrlFetchApp.fetch(
    'https://fonts.gstatic.com/s/i/productlogos/googleg/v6/web-24dp/logo_googleg_color_1x_web_24dp.png',
);

// Sets the image, title, and description for the item.
item.setTitle('Google icon').setHelpText('Google icon').setImage(img);

Возвращаться

Image Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add List Item()

Appends a new question item that allows the respondent to select one choice from a dropdown list.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a dropdown list to the form.
const item = form.addListItem();

// Sets the title to 'Do you prefer cats or dogs?'
item.setTitle('Do you prefer cats or dogs?');

// Sets the description to 'This is description text...'
item.setHelpText('This is description text...');

// Creates and adds choices to the dropdown list.
item.setChoices([item.createChoice('dog'), item.createChoice('cat')]);

Возвращаться

List Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Multiple Choice Item()

Adds a new question item that allows the respondent to select one choice from a list of radio buttons or an optional "other" field.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a multiple choice item to the form.
const item = form.addMultipleChoiceItem();

// Sets the title.
item.setTitle('What is your favorite ice cream flavor?');

// Creates some choice items.
const vanilla = item.createChoice('vanilla');
const chocolate = item.createChoice('chocolate');
const strawberry = item.createChoice('strawberry');

// Sets the choices.
item.setChoices([vanilla, chocolate, strawberry]);

Возвращаться

Multiple Choice Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Page Break Item()

Adds a new layout item that marks the start of a page.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds page break items to create a second and third page for the form.
const pageTwo = form.addPageBreakItem();
const pageThree = form.addPageBreakItem();

// Sets the titles for the pages.
pageTwo.setTitle('Page two');
pageThree.setTitle('Page three');

// Upon completion of the first page, sets the form to navigate to the third
// page.
pageTwo.setGoToPage(pageThree);

// Upon completion of the second page, sets the form to navigate back to the
// first page.
pageThree.setGoToPage(FormApp.PageNavigationType.RESTART);

Возвращаться

Page Break Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Paragraph Text Item()

Adds a new question item that allows the respondent to enter a block of text.

// Opens the form by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds the paragraph text item.
const item = form.addParagraphTextItem();

// Sets the title to 'What is your address?'
item.setTitle('What is your address?');

Возвращаться

Paragraph Text Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Published Reader(emailAddress)

Adds the given user to the list of responders for the Form . If the user was already on the list of editors or viewers, this method has no effect.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Adds responder to the form.
// TODO(developer): replace the emailAddress.
form.addPublishedReader('responder@uni.edu');

Параметры

Имя Тип Описание
email Address String The email address of the user to add.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Published Reader(user)

Adds the given user to the list of responders for the Form . If the user was already on the list of editors or viewers, this method has no effect.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const oldForm = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Gets the responders from the old form.
const users = oldForm.getPublishedReaders();

// Creates a new form.
const newForm = FormApp.create('New form');

// Adds the responders to a new form.
users.forEach(user => newForm.addPublishedReader(user));

Параметры

Имя Тип Описание
user User A representation of the user to add.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Published Readers(emailAddresses)

Adds the given array of users to the list of responders for the Form . If the user was already on the list of editors or viewers, this method has no effect.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Adds responders to the form.
// TODO(developer): replace the emailAddress.
form.addPublishedReaders(['responder1@uni.edu', 'responder2@uni.edu']);

Параметры

Имя Тип Описание
email Addresses String[] An array of email addresses of the users to add.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Rating Item()

Appends a new question item that allows the respondent to give a rating.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds the rating item.
const item = form.addRatingItem();

Возвращаться

Rating Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Scale Item()

Appends a new question item that allows the respondent to choose one option from a numbered sequence of radio buttons.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds the scale item.
const item = form.addScaleItem();

// Sets the title of the scale item to 'Choose a number.'
item.setTitle('Choose a number');

// Sets the scale to 1-5.
item.setBounds(1, 5);

// Sets the label for the lower and upper bounds.
item.setLabels('Lowest', 'Highest');

Возвращаться

Scale Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Section Header Item()

Appends a new layout item that visually indicates the start of a section.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds the section heading item.
const item = form.addSectionHeaderItem();

// Sets the title to 'Title of new section.'
item.setTitle('Title of new section');

// Sets the description.
item.setHelpText('Description of new section');

Возвращаться

Section Header Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Text Item()

Appends a new question item that allows the respondent to enter a single line of text.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a single-line text item.
const item = form.addTextItem();

// Sets the title to 'What is your name?'
item.setTitle('What is your name?');

Возвращаться

Text Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Time Item()

Appends a new question item that allows the respondent to indicate a time of day.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a question with a time input.
const item = form.addTimeItem();

// Sets the title to 'What time do you usually wake up in the morning?'
item.setTitle('What time do you usually wake up in the morning?');

Возвращаться

Time Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Video Item()

Appends a new layout item that displays a video.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a video item.
const item = form.addVideoItem();

// Sets the title, description, and video.
item.setTitle('YouTube video')
    .setHelpText('Send content automatically via Google Sheets and Apps Script')
    .setVideoUrl('https://youtu.be/xxgQr-jSu9o');

// Sets the alignment to the center.
item.setAlignment(FormApp.Alignment.CENTER);

Возвращаться

Video Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

can Edit Response()

Determines whether the form displays a link to edit a response after submitting it.

Regardless of this setting, the method Form Response.getEditResponseUrl() allows a script author who has edit access to the form to generate a URL that can be used to edit a response.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Checks if the form displays a link to edit a response after submitting it.
// The default is false. To let people edit their responses, use
// form.setAllowResponseEdits(true).
const edit = form.canEditResponse();

// If the form doesn't let people edit responses, logs false to the console.
console.log(edit);

Возвращаться

Booleantrue if the form displays an "Edit your response" link; false if it doesn't.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

collects Email()

Determines whether the form collects respondents' email addresses.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to not collect respondents' email addresses.
form.setCollectEmail(false);

// Checks whether the form collects respondents' email addresses and logs it to
// the console.
const bool = form.collectsEmail();

console.log(bool);

Возвращаться

Booleantrue if the form collects email addresses; false if it doesn't.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

create Response()

Creates a new response to the form. To answer a question item, create an Item Response from the item, then attach it to this form response by calling Form Response.withItemResponse(response) . To save the assembled response, call Form Response.submit() .

Возвращаться

Form Response — The newly created form response.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

delete All Responses()

Deletes all submitted responses from the form's response store. This method does not delete copies of responses stored in an external response destination (like a spreadsheet), but does clear the form's summary view.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

delete Item(index)

Deletes the item at a given index among all the items in the form. Throws a scripting exception if no item exists at the given index.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets all the items from the form.
const items = form.getItems();

// Finds the index of a paragraph text item and deletes it by the item's index.
const index = items.findIndex(
    (item) => item.getType() === FormApp.ItemType.PARAGRAPH_TEXT,
);
if (index !== -1) {
  form.deleteItem(index);
}

Параметры

Имя Тип Описание
index Integer The index of the item among all the items in the form.

Throws

Error — if no item exists at the given index

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

delete Item(item)

Deletes the given item. Throws a scripting exception if the item has already been deleted.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets all of the items from the form.
const items = form.getItems();

// Finds a paragraph text item and deletes it.
const item = items.find(
    (item) => item.getType() === FormApp.ItemType.PARAGRAPH_TEXT,
);
if (item) {
  form.deleteItem(item);
}

Параметры

Имя Тип Описание
item Item The item to be deleted.

Throws

Error — if the item does not exist in the form

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

delete Response(responseId)

Deletes a single response from the form's response store. This method does not delete copies of responses stored in an external response destination (like a spreadsheet), but does remove the response from the form's summary view. The response ID can be retrieved with Form Response.getId() .

Параметры

Имя Тип Описание
response Id String The ID of the form response to delete.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Confirmation Message()

Gets the form's confirmation message.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the confirmation message to display after someone submits the form.
form.setConfirmationMessage('You successfully submitted the form.');

// Gets the confirmation message and logs it to the console.
const message = form.getConfirmationMessage();

console.log(message);

Возвращаться

String — The form's confirmation message.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Custom Closed Form Message()

Gets the custom message that is displayed if the form is not accepting responses, or an empty string if no custom message is set.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets a custom closed form message to display to the user when the form
// no longer accepts responses.
form.setCustomClosedFormMessage('The form is no longer accepting responses.');

// Gets the custom message set for the form and logs it to the console.
const message = form.getCustomClosedFormMessage();

console.log(message);

Возвращаться

String — The custom message to display if the form is not accepting responses, or an empty string if no custom message is set.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Description()

Gets the form's description.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form description.
form.setDescription('This is the form description.');

// Gets the form description and logs it to the console.
const description = form.getDescription();

console.log(description);

Возвращаться

String — The form's description.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Destination Id()

Gets the ID of the form's response destination.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Creates a spreadsheet to use as the response destination.
const ss = SpreadsheetApp.create('Test_Spreadsheet');

// Updates the form's response destination.
form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());

// Gets the ID of the form's response destination and logs it to the console.
const destinationId = form.getDestinationId();

console.log(destinationId);

Возвращаться

String — The ID of the form's response destination.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Destination Type()

Gets the type of the form's response destination.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc1234556/edit',
);

// Gets the type of the form's response destination and logs it to the console.
const destinationType = form.getDestinationType().name();

console.log(destinationType);

Возвращаться

Destination Type — The type of the form's response destination.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Edit Url()

Gets the URL that can be used to access the form's edit mode.

// Opens the form by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the URL that accesses the form's edit mode and logs it to the console.
const url = form.getEditUrl();

console.log(url);

Возвращаться

String — The URL to edit the form.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Editors()

Gets the list of editors for this Form .

Возвращаться

User[] — An array of users with edit permission.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Id()

Gets the ID of the form.

// Opens the form by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the ID of the form and logs it to the console.
const id = form.getId();

console.log(id);

Возвращаться

String — The ID of the form.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Item By Id(id)

Gets the item with a given ID. Returns null if the ID does not correspond to an item in the form.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the ID of the first item on the form.
const itemId = form.getItems()[0].getId();

// Gets the item from the ID.
const item = form.getItemById(itemId);

// Gets the name of the item type and logs it to the console.
const type = item.getType().name();

console.log(type);

Параметры

Имя Тип Описание
id Integer The item's ID.

Возвращаться

Item — The item with the given ID, or null if the item does not exist in the form.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Items()

Gets an array of all items in the form.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the list of items in the form.
const items = form.getItems();

// Gets the type for each item and logs them to the console.
const types = items.map((item) => item.getType().name());

console.log(types);

Возвращаться

Item[] — An array of all items in the form.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Items(itemType)

Gets an array of all items of a given type.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets a list of all checkbox items on the form.
const items = form.getItems(FormApp.ItemType.CHECKBOX);

// Gets the title of each checkbox item and logs them to the console.
const checkboxItemsTitle = items.map(
    (item) => item.asCheckboxItem().getTitle(),
);
console.log(checkboxItemsTitle);

Параметры

Имя Тип Описание
item Type Item Type The type of items to retrieve.

Возвращаться

Item[] — An array of all items of that type.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Published Readers()

Gets the list of responders for this Form .

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Gets the responders for the form.
const users = form.getPublishedReaders();
users.forEach(user => console.log(user.getEmail()));

Возвращаться

User[] — An array of users with responder permission.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Published Url()

Gets the URL that can be used to respond to the form.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the URL to respond to the form and logs it to the console.
const url = form.getPublishedUrl();
console.log(url);

Возвращаться

String — The URL to respond to the form.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Response(responseId)

Gets a single form response based on its response ID. Response IDs can be retrieved from Form Response.getId() .

Параметры

Имя Тип Описание
response Id String The ID for the form response.

Возвращаться

Form Response — The form response.

Throws

Error — if the response does not exist

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Responses()

Gets an array of all of the form's responses.

Возвращаться

Form Response[] — An array of all of the form's responses.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Responses(timestamp)

Gets an array of all of the form's responses after a given date and time.

Параметры

Имя Тип Описание
timestamp Date The earliest date and time for which form responses should be returned.

Возвращаться

Form Response[] — The list of form responses.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Shuffle Questions()

Determines whether the order of the questions on each page of the form is randomized.

Возвращаться

Booleantrue if the order of the questions on each page of the form is randomized; false if not.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Summary Url()

Gets the URL that can be used to view a summary of the form's responses. Unless set Publishing Summary(enabled) is set to true , only the users with edit permission to the form is able to access the URL.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// Opens the form by its URL.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the URL to view a summary of the form's responses and logs it to the
// console.
const url = form.getSummaryUrl();
console.log(url);

Возвращаться

String — The URL to view a summary of responses.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Title()

Gets the form's title.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the title of the form to 'For_Testing.'
form.setTitle('For_Testing');

// Gets the title of the form and logs it to the console.
const title = form.getTitle();
console.log(title);

Возвращаться

String — The form's title.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

has Limit One Response Per User()

Determines whether the form allows only one response per respondent. If the value is true , the script cannot submit form responses at all.

Возвращаться

Booleantrue if the form allows only one response per respondent; false if not.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

has Progress Bar()

Determines whether the form displays a progress bar.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// Opens the form by its URL.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Displays the progress bar on the form.
form.setProgressBar(true);

// Checks if the form displays a progress bar and logs it to the console.
console.log(form.hasProgressBar());

Возвращаться

Booleantrue if the form displays a progress bar; false if it doesn't.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

Determines whether the form displays a link to submit another response after a respondent completes the form.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to display a link to submit another
// response after someone submits the form.
form.setShowLinkToRespondAgain(true);

// Checks if the form displays a 'Submit another response' link and logs it to
// the console.
console.log(form.hasRespondAgainLink());

Возвращаться

Booleantrue if the form displays a "Submit another response" link; false if it doesn't.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

is Accepting Responses()

Determines whether the form is currently accepting responses. This is overwritten when the form's publishing state is changed.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to accept responses.
form.setAcceptingResponses(true);

// Checks if the form is accepting responses or not and logs it to the console.
const accepting = form.isAcceptingResponses();
console.log(accepting);

Возвращаться

Booleantrue if the form is accepting responses; false if it isn't.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

is Published()

Determines whether the form is published.

This feature is only available for forms that support publishing. Use supports Advanced Responder Permissions() to check if the form supports publishing.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Checks whether the form is published or not and logs it to the console.
console.log(form.isPublished());

Возвращаться

Booleantrue if the form is published; false if it isn't.

Throws

Error — if called on unsupported forms.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

is Publishing Summary()

Determines whether the form displays a link to view a summary of responses after a respondent completes the form.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to display a link to a summary of
// the responses after someone submits the form.
form.setPublishingSummary(true);

// Checks if the form displays a "See previous responses" link and logs it to
// the console.
const publishingLink = form.isPublishingSummary();
console.log(publishingLink);

Возвращаться

Booleantrue if the form displays a "See previous responses" link; false if it doesn't.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

is Quiz()

Determines whether the form is a quiz.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form as a quiz.
form.setIsQuiz(true);

// Checks if the form is a quiz or not and logs it to the console.
console.log(form.isQuiz());

Возвращаться

Booleantrue if the form is accepting responses; false if it isn't.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

move Item(from, to)

Moves an item at a given index among all the items in the form to another given index. Throws a scripting exception if the to index is out of bounds.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Moves the first item to be the last item.
form.moveItem(0, form.getItems().length - 1);

Параметры

Имя Тип Описание
from Integer The current index of the item among all the items in the form.
to Integer The new index for the item among all the items in the form.

Возвращаться

Item — The item that was moved.

Throws

Error — if either index is out of bounds.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

move Item(item, toIndex)

Moves a given item to a given index among all the items in the form. Throws a scripting exception if the given index is out of bounds.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the first item.
const item = form.getItems()[0];

// Moves the item to be the last item.
form.moveItem(item, form.getItems().length - 1);

Параметры

Имя Тип Описание
item Item The item to move.
to Index Integer The new index for the item among all the items in the form.

Возвращаться

Item — The item that was moved.

Throws

Error — if the index is out of bounds.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

remove Destination()

Unlinks the form from its current response destination. The unlinked former destination still retains a copy of all previous responses. All forms, including those that do not have a destination set explicitly, save a copy of responses in the form's response store . If the form does not currently have a response destination, this method has no effect.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Opens a spreadsheet to use for the response destination.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Updates the form's response destination to the spreadsheet.
form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());

// Unlinks the form from the spreadsheet.
form.removeDestination();

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

remove Editor(emailAddress)

Removes the given user from the list of editors for the Form . This method doesn't block users from accessing the Form if they belong to a class of users who have general access—for example, if the Form is shared with the user's entire domain, or if the Form is in a shared drive that the user can access.

For Drive files, this also removes the user from the list of viewers and responders.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Removes the editor from the form.
// TODO(developer): replace the emailAddress.
form.removeEditor('editor@uni.edu');

Параметры

Имя Тип Описание
email Address String The email address of the user to remove.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

remove Editor(user)

Removes the given user from the list of editors for the Form . This method doesn't block users from accessing the Form if they belong to a class of users who have general access—for example, if the Form is shared with the user's entire domain, or if the Form is in a shared drive that the user can access.

For Drive files, this also removes the user from the list of viewers.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const form1 = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Gets the editors from the form.
const users = form1.getEditors();

// Opens another form.
// TODO(developer): Replace the URL with your own.
const form2 = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Removes editors from the form.
users.forEach(user => form2.removeEditor(user));

Параметры

Имя Тип Описание
user User A representation of the user to remove.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

remove Published Reader(emailAddress)

Removes the given user from the list of responders for the Form . This method doesn't block users from accessing the Form if they belong to a class of users who have general access—for example, if the Form is shared with the user's entire domain, or if the Form is in a shared drive that the user can access.

For Drive files, this also removes the user from the list of viewers and editors.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Removes the responders from the form.
// TODO(developer): replace the emailAddress.
form.removePublishedReader('responder1@uni.edu');

Параметры

Имя Тип Описание
email Address String The email address of the user to remove.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

remove Published Reader(user)

Removes the given user from the list of responders for the Form . This method doesn't block users from accessing the Form if they belong to a class of users who have general access—for example, if the Form is shared with the user's entire domain, or if the Form is in a shared drive that the user can access.

For Drive files, this also removes the user from the list of viewers and editors.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const form1 = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Gets the responders from the form.
const users = form1.getPublishedReaders();

// Opens another form.
// TODO(developer): Replace the URL with your own.
const form2 = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Removes responders from the form.
users.forEach(user => form2.removePublishedReader(user));

Параметры

Имя Тип Описание
user User A representation of the user to remove.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Accepting Responses(enabled)

Sets whether the form is currently accepting responses. The default for new forms is true . The state is overwritten when the publish state of the form is changed.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to accept responses.
form.setAcceptingResponses(true);

// Checks whether the form is accepting responses or not and logs it to the
// console.
console.log(form.isAcceptingResponses());

Параметры

Имя Тип Описание
enabled Boolean true if the form should accept responses; false if it shouldn't.

Возвращаться

Form — This Form , for chaining.

Throws

Error — if enabled on an unpublished form.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Allow Response Edits(enabled)

Sets whether the form displays a link to edit a response after submitting it. The default for new forms is false .

Regardless of this setting, the method Form Response.getEditResponseUrl() allows a script author who has edit permission to the form to generate a URL that can be used to edit a response.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Shows "Edit your response" link after someone submits the form.
form.setAllowResponseEdits(true);

// Checks whether the option to edit the form after a user submits it is set to
// true or not and logs it to the console.
console.log(form.canEditResponse());

Параметры

Имя Тип Описание
enabled Boolean true if the form should display an "Edit your response" link; false if not.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Collect Email(collect)

Sets whether the form collects respondents' email addresses. The default for new forms is false .

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to collect respondents' email addresses.
form.setCollectEmail(true);

// Checks whether the value is set to true or false and logs it to the console.
const collect = form.collectsEmail();
console.log(collect);

Параметры

Имя Тип Описание
collect Boolean true if the form should collect email addresses; false if it doesn't.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Confirmation Message(message)

Sets the form's confirmation message.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets a custom confirmation message to display after someone submits the form.
form.setConfirmationMessage('Your form has been successfully submitted.');

// Gets the confirmation message set for the form and logs it to the console.
const message = form.getConfirmationMessage();
console.log(message);

Параметры

Имя Тип Описание
message String The form's new confirmation message.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Custom Closed Form Message(message)

Sets the message to display if the form is not accepting responses. If no message is set, the form uses a default message.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to not accept responses.
form.setAcceptingResponses(false);

// Sets a custom closed form message to display to the user.
form.setCustomClosedFormMessage('The form is no longer accepting responses.');

// Gets the custom message set for the form and logs it to the console.
const message = form.getCustomClosedFormMessage();
console.log(message);

Параметры

Имя Тип Описание
message String The message to display if the form is not accepting responses.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Description(description)

Sets the form's description.

Параметры

Имя Тип Описание
description String The form's new description.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Destination(type, id)

Sets the destination where form responses are saved. All forms, including those that do not have a destination set explicitly, save a copy of responses in the form's response store .

Параметры

Имя Тип Описание
type Destination Type The type of the form's response destination.
id String The ID of the form's response destination.

Возвращаться

Form — This Form , for chaining.

Throws

Error — if the given destination ID is invalid

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Is Quiz(enabled)

Sets whether the form is a quiz. The default for new forms is false .

Graded questions are only allowed in Quizzes, so setting this to false causes all grading options to be removed from all questions.

Quiz settings are only available in the new Forms UI; making a form a Quiz opts the form into using the new UI.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Makes the form a quiz.
form.setIsQuiz(true);

// Checks whether the form is a quiz or not and logs it to the console.
console.log(form.isQuiz());

Параметры

Имя Тип Описание
enabled Boolean true if quiz features should be enabled for the form; false if not.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Limit One Response Per User(enabled)

Sets whether the form allows only one response per respondent. The default for new forms is false . If the value is set to true , the script cannot submit form responses at all.

Параметры

Имя Тип Описание
enabled Boolean true if the form should allow only one response per respondent; false if not.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Progress Bar(enabled)

Sets whether the form has a progress bar. The default for new forms is false .

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Displays the progress bar on the form.
form.setProgressBar(true);

// Checks whether the form has a progress bar and logs it to the console.
console.log(form.hasProgressBar());

Параметры

Имя Тип Описание
enabled Boolean true if the form displays a progress bar; false if it doesn't.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Published(enabled)

Sets whether the form is published. The default for new forms is true .

This feature is only available for forms that support publishing. Use supports Advanced Responder Permissions() to check if the form supports publishing.

A form needs to be published for it to be accessible to responders. This method supersedes calls to set Accepting Responses(enabled) .

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Publishes the form before sharing it.
form.setPublished(true);

// Checks whether the form is published or not and logs it to the console.
console.log(form.isPublished());

Параметры

Имя Тип Описание
enabled Boolean true if the form should be published, false if not.

Возвращаться

Form — This Form , for chaining.

Throws

Error — if called on unsupported forms.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Publishing Summary(enabled)

Sets whether the form displays a link to view a summary of responses after a respondent submits the form. The default for new forms is false .

Параметры

Имя Тип Описание
enabled Boolean true if the form should display a "See previous responses" link; false if not.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Show Link To Respond Again(enabled)

Sets whether the form displays a link to submit another response after a respondent completes the form. The default for new forms is true .

Параметры

Имя Тип Описание
enabled Boolean true if the form should display a "Submit another response" link; false if not.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Shuffle Questions(shuffle)

Sets whether the order of the questions on each page of the form is randomized.

Параметры

Имя Тип Описание
shuffle Boolean true if the order of the questions on each page of the form should be randomized; false if not.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Title(title)

Sets the form's title.

Параметры

Имя Тип Описание
title String The form's new title.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

shorten Form Url(url)

Converts a long URL for a form to a short URL. Throws an exception if the long URL does not belong to Google Forms.

Параметры

Имя Тип Описание
url String The URL to shorten.

Возвращаться

String — A URL in the form http://goo.gl/forms/1234 .

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

submit Grades(responses)

Submits grades for the given FormResponses.

If your code includes an on Form Submit trigger, calling submit Grades() triggers the on Form Submit condition and causes an infinite loop. To prevent the infinite loop, add code that checks whether grades already exist before calling submit Grades() .

Параметры

Имя Тип Описание
responses Form Response[] An array of all of the form's responses.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

supports Advanced Responder Permissions()

Determines whether the form supports publishing. This method is used to determine whether the set Published(enabled) and is Published() methods, and responder permissions, are available.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Checks whether the form supports publishing or not and logs it to the
// console.
console.log(form.supportsAdvancedResponderPermissions());

Возвращаться

Booleantrue if the form supports publishing; false if it doesn't.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

Deprecated methods


,
Форма

A form that contains overall properties and items. Properties include title, settings, and where responses are stored. Items include question items like checkboxes or radio items, while layout items refer to things like page breaks. Forms can be accessed or created from Form App .

// Open a form by ID and create a new spreadsheet.
const form = FormApp.openById('1234567890abcdefghijklmnopqrstuvwxyz');
const ss = SpreadsheetApp.create('Spreadsheet Name');

// Update form properties via chaining.
form.setTitle('Form Name')
    .setDescription('Description of form')
    .setConfirmationMessage('Thanks for responding!')
    .setAllowResponseEdits(true)
    .setAcceptingResponses(false);

// Update the form's response destination.
form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());

Методы

Метод Return type Brief description
add Checkbox Grid Item() Checkbox Grid Item Appends a new question item, presented as a grid of columns and rows, that allows the respondent to select multiple choices per row from a sequence of checkboxes.
add Checkbox Item() Checkbox Item Appends a new question item that allows the respondent to select one or more checkboxes, as well as an optional "other" field.
add Date Item() Date Item Appends a new question item that allows the respondent to indicate a date.
add Date Time Item() Date Time Item Appends a new question item that allows the respondent to indicate a date and time.
add Duration Item() Duration Item Appends a new question item that allows the respondent to indicate a length of time.
add Editor(emailAddress) Form Adds the given user to the list of editors for the Form .
add Editor(user) Form Adds the given user to the list of editors for the Form .
add Editors(emailAddresses) Form Adds the given array of users to the list of editors for the Form .
add Grid Item() Grid Item Appends a new question item, presented as a grid of columns and rows, that allows the respondent to select one choice per row from a sequence of radio buttons.
add Image Item() Image Item Appends a new layout item that displays an image.
add List Item() List Item Appends a new question item that allows the respondent to select one choice from a dropdown list.
add Multiple Choice Item() Multiple Choice Item Adds a new question item that allows the respondent to select one choice from a list of radio buttons or an optional "other" field.
add Page Break Item() Page Break Item Adds a new layout item that marks the start of a page.
add Paragraph Text Item() Paragraph Text Item Adds a new question item that allows the respondent to enter a block of text.
add Published Reader(emailAddress) Form Adds the given user to the list of responders for the Form .
add Published Reader(user) Form Adds the given user to the list of responders for the Form .
add Published Readers(emailAddresses) Form Adds the given array of users to the list of responders for the Form .
add Rating Item() Rating Item Appends a new question item that allows the respondent to give a rating.
add Scale Item() Scale Item Appends a new question item that allows the respondent to choose one option from a numbered sequence of radio buttons.
add Section Header Item() Section Header Item Appends a new layout item that visually indicates the start of a section.
add Text Item() Text Item Appends a new question item that allows the respondent to enter a single line of text.
add Time Item() Time Item Appends a new question item that allows the respondent to indicate a time of day.
add Video Item() Video Item Appends a new layout item that displays a video.
can Edit Response() Boolean Determines whether the form displays a link to edit a response after submitting it.
collects Email() Boolean Determines whether the form collects respondents' email addresses.
create Response() Form Response Creates a new response to the form.
delete All Responses() Form Deletes all submitted responses from the form's response store.
delete Item(index) void Deletes the item at a given index among all the items in the form.
delete Item(item) void Deletes the given item.
delete Response(responseId) Form Deletes a single response from the form's response store.
get Confirmation Message() String Gets the form's confirmation message.
get Custom Closed Form Message() String Gets the custom message that is displayed if the form is not accepting responses, or an empty string if no custom message is set.
get Description() String Gets the form's description.
get Destination Id() String Gets the ID of the form's response destination.
get Destination Type() Destination Type Gets the type of the form's response destination.
get Edit Url() String Gets the URL that can be used to access the form's edit mode.
get Editors() User[] Gets the list of editors for this Form .
get Id() String Gets the ID of the form.
get Item By Id(id) Item Gets the item with a given ID.
get Items() Item[] Gets an array of all items in the form.
get Items(itemType) Item[] Gets an array of all items of a given type.
get Published Readers() User[] Gets the list of responders for this Form .
get Published Url() String Gets the URL that can be used to respond to the form.
get Response(responseId) Form Response Gets a single form response based on its response ID.
get Responses() Form Response[] Gets an array of all of the form's responses.
get Responses(timestamp) Form Response[] Gets an array of all of the form's responses after a given date and time.
get Shuffle Questions() Boolean Determines whether the order of the questions on each page of the form is randomized.
get Summary Url() String Gets the URL that can be used to view a summary of the form's responses.
get Title() String Gets the form's title.
has Limit One Response Per User() Boolean Determines whether the form allows only one response per respondent.
has Progress Bar() Boolean Determines whether the form displays a progress bar.
has Respond Again Link() Boolean Determines whether the form displays a link to submit another response after a respondent completes the form.
is Accepting Responses() Boolean Determines whether the form is currently accepting responses.
is Published() Boolean Determines whether the form is published.
is Publishing Summary() Boolean Determines whether the form displays a link to view a summary of responses after a respondent completes the form.
is Quiz() Boolean Determines whether the form is a quiz.
move Item(from, to) Item Moves an item at a given index among all the items in the form to another given index.
move Item(item, toIndex) Item Moves a given item to a given index among all the items in the form.
remove Destination() Form Unlinks the form from its current response destination.
remove Editor(emailAddress) Form Removes the given user from the list of editors for the Form .
remove Editor(user) Form Removes the given user from the list of editors for the Form .
remove Published Reader(emailAddress) Form Removes the given user from the list of responders for the Form .
remove Published Reader(user) Form Removes the given user from the list of responders for the Form .
set Accepting Responses(enabled) Form Sets whether the form is currently accepting responses.
set Allow Response Edits(enabled) Form Sets whether the form displays a link to edit a response after submitting it.
set Collect Email(collect) Form Sets whether the form collects respondents' email addresses.
set Confirmation Message(message) Form Sets the form's confirmation message.
set Custom Closed Form Message(message) Form Sets the message to display if the form is not accepting responses.
set Description(description) Form Sets the form's description.
set Destination(type, id) Form Sets the destination where form responses are saved.
set Is Quiz(enabled) Form Sets whether the form is a quiz.
set Limit One Response Per User(enabled) Form Sets whether the form allows only one response per respondent.
set Progress Bar(enabled) Form Sets whether the form has a progress bar.
set Published(enabled) Form Sets whether the form is published.
set Publishing Summary(enabled) Form Sets whether the form displays a link to view a summary of responses after a respondent submits the form.
set Show Link To Respond Again(enabled) Form Sets whether the form displays a link to submit another response after a respondent completes the form.
set Shuffle Questions(shuffle) Form Sets whether the order of the questions on each page of the form is randomized.
set Title(title) Form Sets the form's title.
shorten Form Url(url) String Converts a long URL for a form to a short URL.
submit Grades(responses) Form Submits grades for the given FormResponses.
supports Advanced Responder Permissions() Boolean Determines whether the form supports publishing.

Detailed documentation

add Checkbox Grid Item()

Appends a new question item, presented as a grid of columns and rows, that allows the respondent to select multiple choices per row from a sequence of checkboxes.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a checkbox grid item.
const item = form.addCheckboxGridItem();

item.setTitle('Where did you celebrate New Year\'s?');

// Sets the grid's rows and columns.
item.setRows(['New York', 'San Francisco', 'London']).setColumns([
  '2014', '2015', '2016', '2017'
]);

Возвращаться

Checkbox Grid Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Checkbox Item()

Appends a new question item that allows the respondent to select one or more checkboxes, as well as an optional "other" field.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a checkbox item.
const item = form.addCheckboxItem();

// Sets the title of the checkbox item to 'Do you prefer cats or dogs?'
item.setTitle('Do you prefer cats or dogs?');

// Sets the choices.
item.setChoiceValues(['Cats', 'Dogs']);

Возвращаться

Checkbox Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Date Item()

Appends a new question item that allows the respondent to indicate a date.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a date item.
const item = form.addDateItem();

// Sets the title to 'When were you born?'
item.setTitle('When were you born?');

// Sets the description for the date item.
item.setHelpText('Some helper text.');

Возвращаться

Date Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Date Time Item()

Appends a new question item that allows the respondent to indicate a date and time.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a question with date and time inputs.
const item = form.addDateTimeItem();

// Sets the title to 'When were you born?'
item.setTitle('When were you born?');

// Sets the question as required.
item.setRequired(true);

Возвращаться

Date Time Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Duration Item()

Appends a new question item that allows the respondent to indicate a length of time.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a question with a duration input.
const item = form.addDurationItem();

// Sets the title to 'How long can you hold your breath?'
item.setTitle('How long can you hold your breath?');

// Sets the question as required.
item.setRequired(true);

Возвращаться

Duration Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Editor(emailAddress)

Adds the given user to the list of editors for the Form . If the user was already on the list of viewers or responders, this method promotes the user out of the list.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Adds editor to the form.
// TODO(developer): replace the emailAddress.
form.addEditor('editor@uni.edu');

Параметры

Имя Тип Описание
email Address String The email address of the user to add.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Editor(user)

Adds the given user to the list of editors for the Form . If the user was already on the list of viewers or responders, this method promotes the user out of the list.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const oldForm = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Gets the editors from the old form.
const users = oldForm.getEditors();

// Creates a new form.
const newForm = FormApp.create('New form');

// Adds the editors to a new form.
users.forEach(user => newForm.addEditor(user));

Параметры

Имя Тип Описание
user User A representation of the user to add.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Editors(emailAddresses)

Adds the given array of users to the list of editors for the Form . If any of the users were already on the list of viewers, this method promotes them out of the list of viewers.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Adds editors to the form.
// TODO(developer): replace the emailAddress.
form.addPublishedReaders(['editor1@uni.edu', 'editor2@uni.edu']);

Параметры

Имя Тип Описание
email Addresses String[] An array of email addresses of the users to add.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Grid Item()

Appends a new question item, presented as a grid of columns and rows, that allows the respondent to select one choice per row from a sequence of radio buttons.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a multiple choice grid.
const item = form.addGridItem();

// Sets the title to 'Rate your interests.'
item.setTitle('Rate your interests');

// Sets the grid's rows and columns.
item.setRows(['Cars', 'Computers', 'Celebrities']).setColumns([
  'Boring', 'So-so', 'Interesting'
]);

Возвращаться

Grid Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Image Item()

Appends a new layout item that displays an image.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds an image item.
const item = form.addImageItem();

// Gets the Google icon to use as the image.
const img = UrlFetchApp.fetch(
    'https://fonts.gstatic.com/s/i/productlogos/googleg/v6/web-24dp/logo_googleg_color_1x_web_24dp.png',
);

// Sets the image, title, and description for the item.
item.setTitle('Google icon').setHelpText('Google icon').setImage(img);

Возвращаться

Image Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add List Item()

Appends a new question item that allows the respondent to select one choice from a dropdown list.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a dropdown list to the form.
const item = form.addListItem();

// Sets the title to 'Do you prefer cats or dogs?'
item.setTitle('Do you prefer cats or dogs?');

// Sets the description to 'This is description text...'
item.setHelpText('This is description text...');

// Creates and adds choices to the dropdown list.
item.setChoices([item.createChoice('dog'), item.createChoice('cat')]);

Возвращаться

List Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Multiple Choice Item()

Adds a new question item that allows the respondent to select one choice from a list of radio buttons or an optional "other" field.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a multiple choice item to the form.
const item = form.addMultipleChoiceItem();

// Sets the title.
item.setTitle('What is your favorite ice cream flavor?');

// Creates some choice items.
const vanilla = item.createChoice('vanilla');
const chocolate = item.createChoice('chocolate');
const strawberry = item.createChoice('strawberry');

// Sets the choices.
item.setChoices([vanilla, chocolate, strawberry]);

Возвращаться

Multiple Choice Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Page Break Item()

Adds a new layout item that marks the start of a page.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds page break items to create a second and third page for the form.
const pageTwo = form.addPageBreakItem();
const pageThree = form.addPageBreakItem();

// Sets the titles for the pages.
pageTwo.setTitle('Page two');
pageThree.setTitle('Page three');

// Upon completion of the first page, sets the form to navigate to the third
// page.
pageTwo.setGoToPage(pageThree);

// Upon completion of the second page, sets the form to navigate back to the
// first page.
pageThree.setGoToPage(FormApp.PageNavigationType.RESTART);

Возвращаться

Page Break Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Paragraph Text Item()

Adds a new question item that allows the respondent to enter a block of text.

// Opens the form by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds the paragraph text item.
const item = form.addParagraphTextItem();

// Sets the title to 'What is your address?'
item.setTitle('What is your address?');

Возвращаться

Paragraph Text Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Published Reader(emailAddress)

Adds the given user to the list of responders for the Form . If the user was already on the list of editors or viewers, this method has no effect.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Adds responder to the form.
// TODO(developer): replace the emailAddress.
form.addPublishedReader('responder@uni.edu');

Параметры

Имя Тип Описание
email Address String The email address of the user to add.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Published Reader(user)

Adds the given user to the list of responders for the Form . If the user was already on the list of editors or viewers, this method has no effect.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const oldForm = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Gets the responders from the old form.
const users = oldForm.getPublishedReaders();

// Creates a new form.
const newForm = FormApp.create('New form');

// Adds the responders to a new form.
users.forEach(user => newForm.addPublishedReader(user));

Параметры

Имя Тип Описание
user User A representation of the user to add.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Published Readers(emailAddresses)

Adds the given array of users to the list of responders for the Form . If the user was already on the list of editors or viewers, this method has no effect.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Adds responders to the form.
// TODO(developer): replace the emailAddress.
form.addPublishedReaders(['responder1@uni.edu', 'responder2@uni.edu']);

Параметры

Имя Тип Описание
email Addresses String[] An array of email addresses of the users to add.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Rating Item()

Appends a new question item that allows the respondent to give a rating.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds the rating item.
const item = form.addRatingItem();

Возвращаться

Rating Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Scale Item()

Appends a new question item that allows the respondent to choose one option from a numbered sequence of radio buttons.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds the scale item.
const item = form.addScaleItem();

// Sets the title of the scale item to 'Choose a number.'
item.setTitle('Choose a number');

// Sets the scale to 1-5.
item.setBounds(1, 5);

// Sets the label for the lower and upper bounds.
item.setLabels('Lowest', 'Highest');

Возвращаться

Scale Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Section Header Item()

Appends a new layout item that visually indicates the start of a section.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds the section heading item.
const item = form.addSectionHeaderItem();

// Sets the title to 'Title of new section.'
item.setTitle('Title of new section');

// Sets the description.
item.setHelpText('Description of new section');

Возвращаться

Section Header Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Text Item()

Appends a new question item that allows the respondent to enter a single line of text.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a single-line text item.
const item = form.addTextItem();

// Sets the title to 'What is your name?'
item.setTitle('What is your name?');

Возвращаться

Text Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Time Item()

Appends a new question item that allows the respondent to indicate a time of day.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a question with a time input.
const item = form.addTimeItem();

// Sets the title to 'What time do you usually wake up in the morning?'
item.setTitle('What time do you usually wake up in the morning?');

Возвращаться

Time Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

add Video Item()

Appends a new layout item that displays a video.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Adds a video item.
const item = form.addVideoItem();

// Sets the title, description, and video.
item.setTitle('YouTube video')
    .setHelpText('Send content automatically via Google Sheets and Apps Script')
    .setVideoUrl('https://youtu.be/xxgQr-jSu9o');

// Sets the alignment to the center.
item.setAlignment(FormApp.Alignment.CENTER);

Возвращаться

Video Item — The newly created item.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

can Edit Response()

Determines whether the form displays a link to edit a response after submitting it.

Regardless of this setting, the method Form Response.getEditResponseUrl() allows a script author who has edit access to the form to generate a URL that can be used to edit a response.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Checks if the form displays a link to edit a response after submitting it.
// The default is false. To let people edit their responses, use
// form.setAllowResponseEdits(true).
const edit = form.canEditResponse();

// If the form doesn't let people edit responses, logs false to the console.
console.log(edit);

Возвращаться

Booleantrue if the form displays an "Edit your response" link; false if it doesn't.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

collects Email()

Determines whether the form collects respondents' email addresses.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to not collect respondents' email addresses.
form.setCollectEmail(false);

// Checks whether the form collects respondents' email addresses and logs it to
// the console.
const bool = form.collectsEmail();

console.log(bool);

Возвращаться

Booleantrue if the form collects email addresses; false if it doesn't.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

create Response()

Creates a new response to the form. To answer a question item, create an Item Response from the item, then attach it to this form response by calling Form Response.withItemResponse(response) . To save the assembled response, call Form Response.submit() .

Возвращаться

Form Response — The newly created form response.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

delete All Responses()

Deletes all submitted responses from the form's response store. This method does not delete copies of responses stored in an external response destination (like a spreadsheet), but does clear the form's summary view.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

delete Item(index)

Deletes the item at a given index among all the items in the form. Throws a scripting exception if no item exists at the given index.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets all the items from the form.
const items = form.getItems();

// Finds the index of a paragraph text item and deletes it by the item's index.
const index = items.findIndex(
    (item) => item.getType() === FormApp.ItemType.PARAGRAPH_TEXT,
);
if (index !== -1) {
  form.deleteItem(index);
}

Параметры

Имя Тип Описание
index Integer The index of the item among all the items in the form.

Throws

Error — if no item exists at the given index

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

delete Item(item)

Deletes the given item. Throws a scripting exception if the item has already been deleted.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets all of the items from the form.
const items = form.getItems();

// Finds a paragraph text item and deletes it.
const item = items.find(
    (item) => item.getType() === FormApp.ItemType.PARAGRAPH_TEXT,
);
if (item) {
  form.deleteItem(item);
}

Параметры

Имя Тип Описание
item Item The item to be deleted.

Throws

Error — if the item does not exist in the form

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

delete Response(responseId)

Deletes a single response from the form's response store. This method does not delete copies of responses stored in an external response destination (like a spreadsheet), but does remove the response from the form's summary view. The response ID can be retrieved with Form Response.getId() .

Параметры

Имя Тип Описание
response Id String The ID of the form response to delete.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Confirmation Message()

Gets the form's confirmation message.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the confirmation message to display after someone submits the form.
form.setConfirmationMessage('You successfully submitted the form.');

// Gets the confirmation message and logs it to the console.
const message = form.getConfirmationMessage();

console.log(message);

Возвращаться

String — The form's confirmation message.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Custom Closed Form Message()

Gets the custom message that is displayed if the form is not accepting responses, or an empty string if no custom message is set.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets a custom closed form message to display to the user when the form
// no longer accepts responses.
form.setCustomClosedFormMessage('The form is no longer accepting responses.');

// Gets the custom message set for the form and logs it to the console.
const message = form.getCustomClosedFormMessage();

console.log(message);

Возвращаться

String — The custom message to display if the form is not accepting responses, or an empty string if no custom message is set.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Description()

Gets the form's description.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form description.
form.setDescription('This is the form description.');

// Gets the form description and logs it to the console.
const description = form.getDescription();

console.log(description);

Возвращаться

String — The form's description.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Destination Id()

Gets the ID of the form's response destination.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Creates a spreadsheet to use as the response destination.
const ss = SpreadsheetApp.create('Test_Spreadsheet');

// Updates the form's response destination.
form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());

// Gets the ID of the form's response destination and logs it to the console.
const destinationId = form.getDestinationId();

console.log(destinationId);

Возвращаться

String — The ID of the form's response destination.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Destination Type()

Gets the type of the form's response destination.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc1234556/edit',
);

// Gets the type of the form's response destination and logs it to the console.
const destinationType = form.getDestinationType().name();

console.log(destinationType);

Возвращаться

Destination Type — The type of the form's response destination.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Edit Url()

Gets the URL that can be used to access the form's edit mode.

// Opens the form by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the URL that accesses the form's edit mode and logs it to the console.
const url = form.getEditUrl();

console.log(url);

Возвращаться

String — The URL to edit the form.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Editors()

Gets the list of editors for this Form .

Возвращаться

User[] — An array of users with edit permission.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Id()

Gets the ID of the form.

// Opens the form by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the ID of the form and logs it to the console.
const id = form.getId();

console.log(id);

Возвращаться

String — The ID of the form.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Item By Id(id)

Gets the item with a given ID. Returns null if the ID does not correspond to an item in the form.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the ID of the first item on the form.
const itemId = form.getItems()[0].getId();

// Gets the item from the ID.
const item = form.getItemById(itemId);

// Gets the name of the item type and logs it to the console.
const type = item.getType().name();

console.log(type);

Параметры

Имя Тип Описание
id Integer The item's ID.

Возвращаться

Item — The item with the given ID, or null if the item does not exist in the form.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Items()

Gets an array of all items in the form.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the list of items in the form.
const items = form.getItems();

// Gets the type for each item and logs them to the console.
const types = items.map((item) => item.getType().name());

console.log(types);

Возвращаться

Item[] — An array of all items in the form.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Items(itemType)

Gets an array of all items of a given type.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets a list of all checkbox items on the form.
const items = form.getItems(FormApp.ItemType.CHECKBOX);

// Gets the title of each checkbox item and logs them to the console.
const checkboxItemsTitle = items.map(
    (item) => item.asCheckboxItem().getTitle(),
);
console.log(checkboxItemsTitle);

Параметры

Имя Тип Описание
item Type Item Type The type of items to retrieve.

Возвращаться

Item[] — An array of all items of that type.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Published Readers()

Gets the list of responders for this Form .

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Gets the responders for the form.
const users = form.getPublishedReaders();
users.forEach(user => console.log(user.getEmail()));

Возвращаться

User[] — An array of users with responder permission.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Published Url()

Gets the URL that can be used to respond to the form.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the URL to respond to the form and logs it to the console.
const url = form.getPublishedUrl();
console.log(url);

Возвращаться

String — The URL to respond to the form.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Response(responseId)

Gets a single form response based on its response ID. Response IDs can be retrieved from Form Response.getId() .

Параметры

Имя Тип Описание
response Id String The ID for the form response.

Возвращаться

Form Response — The form response.

Throws

Error — if the response does not exist

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Responses()

Gets an array of all of the form's responses.

Возвращаться

Form Response[] — An array of all of the form's responses.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Responses(timestamp)

Gets an array of all of the form's responses after a given date and time.

Параметры

Имя Тип Описание
timestamp Date The earliest date and time for which form responses should be returned.

Возвращаться

Form Response[] — The list of form responses.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Shuffle Questions()

Determines whether the order of the questions on each page of the form is randomized.

Возвращаться

Booleantrue if the order of the questions on each page of the form is randomized; false if not.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Summary Url()

Gets the URL that can be used to view a summary of the form's responses. Unless set Publishing Summary(enabled) is set to true , only the users with edit permission to the form is able to access the URL.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// Opens the form by its URL.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the URL to view a summary of the form's responses and logs it to the
// console.
const url = form.getSummaryUrl();
console.log(url);

Возвращаться

String — The URL to view a summary of responses.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

get Title()

Gets the form's title.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the title of the form to 'For_Testing.'
form.setTitle('For_Testing');

// Gets the title of the form and logs it to the console.
const title = form.getTitle();
console.log(title);

Возвращаться

String — The form's title.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

has Limit One Response Per User()

Determines whether the form allows only one response per respondent. If the value is true , the script cannot submit form responses at all.

Возвращаться

Booleantrue if the form allows only one response per respondent; false if not.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

has Progress Bar()

Determines whether the form displays a progress bar.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// Opens the form by its URL.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Displays the progress bar on the form.
form.setProgressBar(true);

// Checks if the form displays a progress bar and logs it to the console.
console.log(form.hasProgressBar());

Возвращаться

Booleantrue if the form displays a progress bar; false if it doesn't.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

Determines whether the form displays a link to submit another response after a respondent completes the form.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to display a link to submit another
// response after someone submits the form.
form.setShowLinkToRespondAgain(true);

// Checks if the form displays a 'Submit another response' link and logs it to
// the console.
console.log(form.hasRespondAgainLink());

Возвращаться

Booleantrue if the form displays a "Submit another response" link; false if it doesn't.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

is Accepting Responses()

Determines whether the form is currently accepting responses. This is overwritten when the form's publishing state is changed.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to accept responses.
form.setAcceptingResponses(true);

// Checks if the form is accepting responses or not and logs it to the console.
const accepting = form.isAcceptingResponses();
console.log(accepting);

Возвращаться

Booleantrue if the form is accepting responses; false if it isn't.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

is Published()

Determines whether the form is published.

This feature is only available for forms that support publishing. Use supports Advanced Responder Permissions() to check if the form supports publishing.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Checks whether the form is published or not and logs it to the console.
console.log(form.isPublished());

Возвращаться

Booleantrue if the form is published; false if it isn't.

Throws

Error — if called on unsupported forms.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

is Publishing Summary()

Determines whether the form displays a link to view a summary of responses after a respondent completes the form.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to display a link to a summary of
// the responses after someone submits the form.
form.setPublishingSummary(true);

// Checks if the form displays a "See previous responses" link and logs it to
// the console.
const publishingLink = form.isPublishingSummary();
console.log(publishingLink);

Возвращаться

Booleantrue if the form displays a "See previous responses" link; false if it doesn't.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

is Quiz()

Determines whether the form is a quiz.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form as a quiz.
form.setIsQuiz(true);

// Checks if the form is a quiz or not and logs it to the console.
console.log(form.isQuiz());

Возвращаться

Booleantrue if the form is accepting responses; false if it isn't.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

move Item(from, to)

Moves an item at a given index among all the items in the form to another given index. Throws a scripting exception if the to index is out of bounds.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Moves the first item to be the last item.
form.moveItem(0, form.getItems().length - 1);

Параметры

Имя Тип Описание
from Integer The current index of the item among all the items in the form.
to Integer The new index for the item among all the items in the form.

Возвращаться

Item — The item that was moved.

Throws

Error — if either index is out of bounds.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

move Item(item, toIndex)

Moves a given item to a given index among all the items in the form. Throws a scripting exception if the given index is out of bounds.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Gets the first item.
const item = form.getItems()[0];

// Moves the item to be the last item.
form.moveItem(item, form.getItems().length - 1);

Параметры

Имя Тип Описание
item Item The item to move.
to Index Integer The new index for the item among all the items in the form.

Возвращаться

Item — The item that was moved.

Throws

Error — if the index is out of bounds.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

remove Destination()

Unlinks the form from its current response destination. The unlinked former destination still retains a copy of all previous responses. All forms, including those that do not have a destination set explicitly, save a copy of responses in the form's response store . If the form does not currently have a response destination, this method has no effect.

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Opens a spreadsheet to use for the response destination.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl(
    'https://docs.google.com/spreadsheets/d/abc123456/edit',
);

// Updates the form's response destination to the spreadsheet.
form.setDestination(FormApp.DestinationType.SPREADSHEET, ss.getId());

// Unlinks the form from the spreadsheet.
form.removeDestination();

Возвращаться

Form — This Form , for chaining.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

remove Editor(emailAddress)

Removes the given user from the list of editors for the Form . This method doesn't block users from accessing the Form if they belong to a class of users who have general access—for example, if the Form is shared with the user's entire domain, or if the Form is in a shared drive that the user can access.

For Drive files, this also removes the user from the list of viewers and responders.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Removes the editor from the form.
// TODO(developer): replace the emailAddress.
form.removeEditor('editor@uni.edu');

Параметры

Имя Тип Описание
email Address String The email address of the user to remove.

Возвращаться

Form — This Form , for chaining.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

remove Editor(user)

Removes the given user from the list of editors for the Form . This method doesn't block users from accessing the Form if they belong to a class of users who have general access—for example, if the Form is shared with the user's entire domain, or if the Form is in a shared drive that the user can access.

For Drive files, this also removes the user from the list of viewers.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const form1 = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Gets the editors from the form.
const users = form1.getEditors();

// Opens another form.
// TODO(developer): Replace the URL with your own.
const form2 = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Removes editors from the form.
users.forEach(user => form2.removeEditor(user));

Параметры

Имя Тип Описание
user User A representation of the user to remove.

Возвращаться

Form — This Form , for chaining.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

remove Published Reader(emailAddress)

Removes the given user from the list of responders for the Form . This method doesn't block users from accessing the Form if they belong to a class of users who have general access—for example, if the Form is shared with the user's entire domain, or if the Form is in a shared drive that the user can access.

For Drive files, this also removes the user from the list of viewers and editors.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Removes the responders from the form.
// TODO(developer): replace the emailAddress.
form.removePublishedReader('responder1@uni.edu');

Параметры

Имя Тип Описание
email Address String The email address of the user to remove.

Возвращаться

Form — This Form , for chaining.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

remove Published Reader(user)

Removes the given user from the list of responders for the Form . This method doesn't block users from accessing the Form if they belong to a class of users who have general access—for example, if the Form is shared with the user's entire domain, or if the Form is in a shared drive that the user can access.

For Drive files, this also removes the user from the list of viewers and editors.

// Opens the Forms file by its URL.
// TODO(developer): Replace the URL with your own.
const form1 = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Gets the responders from the form.
const users = form1.getPublishedReaders();

// Opens another form.
// TODO(developer): Replace the URL with your own.
const form2 = FormApp.openByUrl('https://docs.google.com/forms/d/abc123456/edit');

// Removes responders from the form.
users.forEach(user => form2.removePublishedReader(user));

Параметры

Имя Тип Описание
user User A representation of the user to remove.

Возвращаться

Form — This Form , for chaining.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Accepting Responses(enabled)

Sets whether the form is currently accepting responses. The default for new forms is true . The state is overwritten when the publish state of the form is changed.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to accept responses.
form.setAcceptingResponses(true);

// Checks whether the form is accepting responses or not and logs it to the
// console.
console.log(form.isAcceptingResponses());

Параметры

Имя Тип Описание
enabled Boolean true if the form should accept responses; false if it shouldn't.

Возвращаться

Form — This Form , for chaining.

Throws

Error — if enabled on an unpublished form.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Allow Response Edits(enabled)

Sets whether the form displays a link to edit a response after submitting it. The default for new forms is false .

Regardless of this setting, the method Form Response.getEditResponseUrl() allows a script author who has edit permission to the form to generate a URL that can be used to edit a response.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Shows "Edit your response" link after someone submits the form.
form.setAllowResponseEdits(true);

// Checks whether the option to edit the form after a user submits it is set to
// true or not and logs it to the console.
console.log(form.canEditResponse());

Параметры

Имя Тип Описание
enabled Boolean true if the form should display an "Edit your response" link; false if not.

Возвращаться

Form — This Form , for chaining.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Collect Email(collect)

Sets whether the form collects respondents' email addresses. The default for new forms is false .

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to collect respondents' email addresses.
form.setCollectEmail(true);

// Checks whether the value is set to true or false and logs it to the console.
const collect = form.collectsEmail();
console.log(collect);

Параметры

Имя Тип Описание
collect Boolean true if the form should collect email addresses; false if it doesn't.

Возвращаться

Form — This Form , for chaining.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Confirmation Message(message)

Sets the form's confirmation message.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets a custom confirmation message to display after someone submits the form.
form.setConfirmationMessage('Your form has been successfully submitted.');

// Gets the confirmation message set for the form and logs it to the console.
const message = form.getConfirmationMessage();
console.log(message);

Параметры

Имя Тип Описание
message String The form's new confirmation message.

Возвращаться

Form — This Form , for chaining.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Custom Closed Form Message(message)

Sets the message to display if the form is not accepting responses. If no message is set, the form uses a default message.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Sets the form to not accept responses.
form.setAcceptingResponses(false);

// Sets a custom closed form message to display to the user.
form.setCustomClosedFormMessage('The form is no longer accepting responses.');

// Gets the custom message set for the form and logs it to the console.
const message = form.getCustomClosedFormMessage();
console.log(message);

Параметры

Имя Тип Описание
message String The message to display if the form is not accepting responses.

Возвращаться

Form — This Form , for chaining.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Description(description)

Sets the form's description.

Параметры

Имя Тип Описание
description String The form's new description.

Возвращаться

Form — This Form , for chaining.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Destination(type, id)

Sets the destination where form responses are saved. All forms, including those that do not have a destination set explicitly, save a copy of responses in the form's response store .

Параметры

Имя Тип Описание
type Destination Type The type of the form's response destination.
id String The ID of the form's response destination.

Возвращаться

Form — This Form , for chaining.

Throws

Error — if the given destination ID is invalid

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Is Quiz(enabled)

Sets whether the form is a quiz. The default for new forms is false .

Graded questions are only allowed in Quizzes, so setting this to false causes all grading options to be removed from all questions.

Quiz settings are only available in the new Forms UI; making a form a Quiz opts the form into using the new UI.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Makes the form a quiz.
form.setIsQuiz(true);

// Checks whether the form is a quiz or not and logs it to the console.
console.log(form.isQuiz());

Параметры

Имя Тип Описание
enabled Boolean true if quiz features should be enabled for the form; false if not.

Возвращаться

Form — This Form , for chaining.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Limit One Response Per User(enabled)

Sets whether the form allows only one response per respondent. The default for new forms is false . If the value is set to true , the script cannot submit form responses at all.

Параметры

Имя Тип Описание
enabled Boolean true if the form should allow only one response per respondent; false if not.

Возвращаться

Form — This Form , for chaining.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Progress Bar(enabled)

Sets whether the form has a progress bar. The default for new forms is false .

// Opens the Forms file by its URL. If you created your script from within
// a Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Displays the progress bar on the form.
form.setProgressBar(true);

// Checks whether the form has a progress bar and logs it to the console.
console.log(form.hasProgressBar());

Параметры

Имя Тип Описание
enabled Boolean true if the form displays a progress bar; false if it doesn't.

Возвращаться

Form — This Form , for chaining.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Published(enabled)

Sets whether the form is published. The default for new forms is true .

This feature is only available for forms that support publishing. Use supports Advanced Responder Permissions() to check if the form supports publishing.

A form needs to be published for it to be accessible to responders. This method supersedes calls to set Accepting Responses(enabled) .

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Publishes the form before sharing it.
form.setPublished(true);

// Checks whether the form is published or not and logs it to the console.
console.log(form.isPublished());

Параметры

Имя Тип Описание
enabled Boolean true if the form should be published, false if not.

Возвращаться

Form — This Form , for chaining.

Throws

Error — if called on unsupported forms.

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Publishing Summary(enabled)

Sets whether the form displays a link to view a summary of responses after a respondent submits the form. The default for new forms is false .

Параметры

Имя Тип Описание
enabled Boolean true if the form should display a "See previous responses" link; false if not.

Возвращаться

Form — This Form , for chaining.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Show Link To Respond Again(enabled)

Sets whether the form displays a link to submit another response after a respondent completes the form. The default for new forms is true .

Параметры

Имя Тип Описание
enabled Boolean true if the form should display a "Submit another response" link; false if not.

Возвращаться

Form — This Form , for chaining.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Shuffle Questions(shuffle)

Sets whether the order of the questions on each page of the form is randomized.

Параметры

Имя Тип Описание
shuffle Boolean true if the order of the questions on each page of the form should be randomized; false if not.

Возвращаться

Form — This Form , for chaining.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

set Title(title)

Sets the form's title.

Параметры

Имя Тип Описание
title String The form's new title.

Возвращаться

Form — This Form , for chaining.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

shorten Form Url(url)

Converts a long URL for a form to a short URL. Throws an exception if the long URL does not belong to Google Forms.

Параметры

Имя Тип Описание
url String The URL to shorten.

Возвращаться

String — A URL in the form http://goo.gl/forms/1234 .

Авторизация

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

submit Grades(responses)

Submits grades for the given FormResponses.

If your code includes an on Form Submit trigger, calling submit Grades() triggers the on Form Submit condition and causes an infinite loop. To prevent the infinite loop, add code that checks whether grades already exist before calling submit Grades() .

Параметры

Имя Тип Описание
responses Form Response[] An array of all of the form's responses.

Возвращаться

Form — This Form , for chaining.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

supports Advanced Responder Permissions()

Determines whether the form supports publishing. This method is used to determine whether the set Published(enabled) and is Published() methods, and responder permissions, are available.

// Opens the Forms file by its URL. If you created your script from within a
// Google Forms file, you can use FormApp.getActiveForm() instead.
// TODO(developer): Replace the URL with your own.
const form = FormApp.openByUrl(
    'https://docs.google.com/forms/d/abc123456/edit',
);

// Checks whether the form supports publishing or not and logs it to the
// console.
console.log(form.supportsAdvancedResponderPermissions());

Возвращаться

Booleantrue if the form supports publishing; false if it doesn't.

Authorization

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

  • https://www.googleapis.com/auth/forms.currentonly
  • https://www.googleapis.com/auth/forms

Deprecated methods