Class Protection

Защита

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

// Protect range A1:B10, then remove all other users from the list of editors.
var ss = SpreadsheetApp.getActive();
var range = ss.getRange('A1:B10');
var protection = range.protect().setDescription('Sample protected range');

// Ensure the current user is an editor before removing others. Otherwise, if the user's edit
// permission comes from a group, the script throws an exception upon removing the group.
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
  protection.setDomainEdit(false);
}
// Remove all range protections in the spreadsheet that the user has permission to edit.
var ss = SpreadsheetApp.getActive();
var protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
for (var i = 0; i < protections.length; i++) {
  var protection = protections[i];
  if (protection.canEdit()) {
    protection.remove();
  }
}
// Protect the active sheet, then remove all other users from the list of editors.
var sheet = SpreadsheetApp.getActiveSheet();
var protection = sheet.protect().setDescription('Sample protected sheet');

// Ensure the current user is an editor before removing others. Otherwise, if the user's edit
// permission comes from a group, the script throws an exception upon removing the group.
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
  protection.setDomainEdit(false);
}

Методы

Метод Тип возврата Краткое описание
addEditor(emailAddress) Protection Добавляет данного пользователя в список редакторов защищенного листа или диапазона.
addEditor(user) Protection Добавляет данного пользователя в список редакторов защищенного листа или диапазона.
addEditors(emailAddresses) Protection Добавляет заданный массив пользователей в список редакторов защищенного листа или диапазона.
addTargetAudience(audienceId) Protection Добавляет указанную целевую аудиторию в качестве редактора защищенного диапазона.
canDomainEdit() Boolean Определяет, имеют ли все пользователи домена, которому принадлежит электронная таблица, разрешение на редактирование защищенного диапазона или листа.
canEdit() Boolean Определяет, есть ли у пользователя разрешение на редактирование защищенного диапазона или листа.
getDescription() String Получает описание защищенного диапазона или листа.
getEditors() User[] Получает список редакторов для защищенного диапазона или листа.
getProtectionType() ProtectionType Получает тип защищаемой области: RANGE или SHEET .
getRange() Range Получает защищаемый диапазон.
getRangeName() String Получает имя защищенного диапазона, если он связан с именованным диапазоном.
getTargetAudiences() TargetAudience[] Возвращает идентификаторы целевых аудиторий, которые могут редактировать защищенный диапазон.
getUnprotectedRanges() Range[] Получает массив незащищенных диапазонов на защищенном листе.
isWarningOnly() Boolean Определяет, использует ли защищенная область защиту «на основе предупреждений».
remove() void Снимает защиту диапазона или листа.
removeEditor(emailAddress) Protection Удаляет данного пользователя из списка редакторов защищенного листа или диапазона.
removeEditor(user) Protection Удаляет данного пользователя из списка редакторов защищенного листа или диапазона.
removeEditors(emailAddresses) Protection Удаляет заданный массив пользователей из списка редакторов защищенного листа или диапазона.
removeTargetAudience(audienceId) Protection Удаляет указанную целевую аудиторию в качестве редактора защищенного диапазона.
setDescription(description) Protection Задает описание защищенного диапазона или листа.
setDomainEdit(editable) Protection Определяет, имеют ли все пользователи домена, которому принадлежит электронная таблица, разрешение на редактирование защищенного диапазона или листа.
setNamedRange(namedRange) Protection Связывает защищенный диапазон с существующим именованным диапазоном.
setRange(range) Protection Регулирует защищаемый диапазон.
setRangeName(rangeName) Protection Связывает защищенный диапазон с существующим именованным диапазоном.
setUnprotectedRanges(ranges) Protection Снимает защиту с данного массива диапазонов внутри защищенного листа.
setWarningOnly(warningOnly) Protection Устанавливает, использует ли этот защищенный диапазон защиту «на основе предупреждений».

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

addEditor(emailAddress)

Добавляет данного пользователя в список редакторов защищенного листа или диапазона. Этот метод не дает пользователю автоматически разрешения на редактирование самой электронной таблицы; чтобы сделать это дополнительно, вызовите Spreadsheet.addEditor(emailAddress) .

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Adds an editor to the spreadsheet using an email address.
// TODO(developer): Replace the email address with a valid email.
ss.addEditor('cloudysanfrancisco@gmail.com');

// Gets a sheet by its name and protects it.
const sheet = ss.getSheetByName('Sheet1');
const sampleProtectedSheet = sheet.protect();

// Adds an editor of the protected sheet using an email address.
// TODO(developer): Replace the email address with a valid email.
sampleProtectedSheet.addEditor('cloudysanfrancisco@gmail.com');

// Gets the editors of the protected sheet.
const editors = sampleProtectedSheet.getEditors();

// Logs the editors' email addresses to the console.
for (const editor of editors) {
  console.log(editor.getEmail());
}

Параметры

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

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

Protection — объект, представляющий настройки защиты для цепочки.

Авторизация

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

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

addEditor(user)

Добавляет данного пользователя в список редакторов защищенного листа или диапазона. Этот метод не дает пользователю автоматически разрешения на редактирование самой электронной таблицы; чтобы сделать это дополнительно, вызовите Spreadsheet.addEditor(user) .

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Gets a sheet by its name.
const sheet = ss.getSheetByName('Sheet1');

// Protects the sheet.
const sampleProtectedSheet = sheet.protect();

// Adds the active user as an editor of the protected sheet.
sampleProtectedSheet.addEditor(Session.getActiveUser());

// Gets the editors of the protected sheet.
const editors = sampleProtectedSheet.getEditors();

// Logs the editors' email addresses to the console.
for (const editor of editors) {
  console.log(editor.getEmail());
}

Параметры

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

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

Protection — объект, представляющий настройки защиты для цепочки.

Авторизация

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

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

addEditors(emailAddresses)

Добавляет заданный массив пользователей в список редакторов защищенного листа или диапазона. Этот метод не дает пользователям автоматически разрешение на редактирование самой электронной таблицы; чтобы сделать это дополнительно, вызовите Spreadsheet.addEditors(emailAddresses) .

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Gets a sheet by its name.
const sheet = ss.getSheetByName('Sheet1');

// Creates variables for the email addresses to add as editors.
// TODO(developer): Replace the email addresses with valid ones.
const TEST_EMAIL_1 = 'cloudysanfrancisco@gmail.com';
const TEST_EMAIL_2 = 'baklavainthebalkans@gmail.com';

// Protects the sheet.
const sampleProtectedSheet = sheet.protect();

// Adds editors to the protected sheet using the email address variables.
sampleProtectedSheet.addEditors([TEST_EMAIL_1, TEST_EMAIL_2]);

// Gets the editors of the protected sheet.
const editors = sampleProtectedSheet.getEditors();

// Logs the editors' email addresses to the console.
for (const editor of editors) {
  console.log(editor.getEmail());
}

Параметры

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

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

Protection — объект, представляющий настройки защиты для цепочки.

Авторизация

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

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

addTargetAudience(audienceId)

Добавляет указанную целевую аудиторию в качестве редактора защищенного диапазона.

Параметры

Имя Тип Описание
audienceId String Идентификатор целевой аудитории, которую нужно добавить.

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

Protection — объект, представляющий настройки защиты для цепочки.

Авторизация

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

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

canDomainEdit()

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

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Gets a sheet by its name.
const sheet = ss.getSheetByName('Sheet1');

// Protects the sheet.
const sampleProtectedSheet = sheet.protect();

// Logs whether domain users have permission to edit the protected sheet to the console.
console.log(sampleProtectedSheet.canDomainEdit());

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

Booleantrue , если все пользователи в домене, которому принадлежит электронная таблица, имеют разрешение на редактирование защищенного диапазона или листа; false , если они этого не делают.

Авторизация

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

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

canEdit()

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

// Remove all range protections in the spreadsheet that the user has permission to edit.
var ss = SpreadsheetApp.getActive();
var protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
for (var i = 0; i < protections.length; i++) {
  var protection = protections[i];
  if (protection.canEdit()) {
    protection.remove();
  }
}

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

Booleantrue , если у пользователя есть разрешение на редактирование защищенного диапазона или листа; false если нет

Авторизация

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

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

getDescription()

Получает описание защищенного диапазона или листа. Если описание не задано, этот метод возвращает пустую строку.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Gets a sheet by its name.
const sheet = ss.getSheetByName('Sheet1');

// Protects the sheet and sets the description.
const sampleProtectedSheet = sheet.protect().setDescription('Sample sheet is protected');

// Gets the description of the protected sheet and logs it to the console.
const sampleProtectedSheetDescription = sampleProtectedSheet.getDescription();
console.log(sampleProtectedSheetDescription);

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

String — описание защищенного диапазона или листа или пустая строка, если описание не задано.

Авторизация

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

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

getEditors()

Получает список редакторов для защищенного диапазона или листа. Выдает исключение, если у пользователя нет разрешения на редактирование защищенного диапазона или листа.

// Protect the active sheet, then remove all other users from the list of editors.
var sheet = SpreadsheetApp.getActiveSheet();
var protection = sheet.protect().setDescription('Sample protected sheet');

// Ensure the current user is an editor before removing others. Otherwise, if the user's edit
// permission comes from a group, the script throws an exception upon removing the group.
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
  protection.setDomainEdit(false);
}

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

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

Авторизация

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

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

getProtectionType()

Получает тип защищаемой области: RANGE или SHEET .

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Gets a sheet by its name.
const sheet = ss.getSheetByName('Sheet1');

// Protects the sheet.
const sampleProtectedSheet = sheet.protect();

// Gets the type of the protected area.
const protectionType = sampleProtectedSheet.getProtectionType();

// Logs 'SHEET'to the console since the type of the protected area is a sheet.
console.log(protectionType.toString());

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

ProtectionType — Тип защищенной области: RANGE или SHEET .

Авторизация

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

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

getRange()

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

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Gets a sheet by its name.
const sheet = ss.getSheetByName('Sheet1');

// Gets the range 'A1:B10' of Sheet1.
const range = sheet.getRange('A1:B10');

// Makes cells A1:B10 a protected range.
const sampleProtectedRange = range.protect();

// Gets the protected ranges on the sheet.
const protections = sheet.getProtections(SpreadsheetApp.ProtectionType.RANGE);

// Logs the A1 notation of the first protected range on the sheet.
console.log(protections[0].getRange().getA1Notation());

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

Range — диапазон, который защищается.

Авторизация

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

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

getRangeName()

Получает имя защищенного диапазона, если он связан с именованным диапазоном. Возвращает null , если защита не связана с именованным диапазоном. Обратите внимание, что сценарии должны явно вызывать setRangeName(rangeName) , чтобы связать защищенный диапазон с именованным диапазоном; вызова Range.protect() для создания защиты из Range , который является именованным диапазоном, без вызова setRangeName(rangeName) недостаточно для их связывания. Однако создание защищенного диапазона из именованного диапазона в пользовательском интерфейсе Google Sheets автоматически связывает их.

// Protect a named range in a spreadsheet and log the name of the protected range.
var ss = SpreadsheetApp.getActive();
var range = ss.getRange('A1:B10');
var protection = range.protect();
ss.setNamedRange('Test', range);       // Create a named range.
protection.setRangeName('Test');       // Associate the protection with the named range.
Logger.log(protection.getRangeName()); // Verify the name of the protected range.

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

String — имя защищенного именованного диапазона или null , если защищенный диапазон не связан с именованным диапазоном.

Авторизация

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

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

getTargetAudiences()

Возвращает идентификаторы целевых аудиторий, которые могут редактировать защищенный диапазон.

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

TargetAudience[] — Массив идентификаторов целевых аудиторий.

Авторизация

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

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

getUnprotectedRanges()

Получает массив незащищенных диапазонов на защищенном листе. Если объект Protection соответствует защищенному диапазону, а не защищенному листу, этот метод возвращает пустой массив. Чтобы изменить незащищенные диапазоны, используйте setUnprotectedRanges(ranges) чтобы установить новый массив диапазонов; чтобы повторно защитить весь лист, установите пустой массив.

// Unprotect cells E2:F5 in addition to any other unprotected ranges in the protected sheet.
var sheet = SpreadsheetApp.getActiveSheet();
var protection = sheet.protect();
var unprotected = protection.getUnprotectedRanges();
unprotected.push(sheet.getRange('E2:F5'));
protection.setUnprotectedRanges(unprotected);

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

Range[] — массив незащищенных диапазонов внутри защищенного листа.

Авторизация

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

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

isWarningOnly()

Определяет, использует ли защищенная область защиту «на основе предупреждений». Защита на основе предупреждений означает, что каждый пользователь может редактировать данные в области, за исключением того, что при редактировании отображается предупреждение с просьбой подтвердить редактирование. По умолчанию защищенные диапазоны или листы не основаны на предупреждениях. Чтобы перейти в состояние предупреждения, используйте setWarningOnly(warningOnly) .

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit')

// Gets a sheet by its name.
const sheet = ss.getSheetByName('Sheet1');

// Protects the sheet.
const sampleProtectedSheet = sheet.protect();

// Sets the warning status for the protected sheet as true.
sampleProtectedSheet.setWarningOnly(true);

const protectedSheetWarningStatus = sampleProtectedSheet.isWarningOnly();

// Logs the warning status of the protected sheet to the console.
console.log(protectedSheetWarningStatus);

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

Booleantrue , если защищенный диапазон или лист использует только защиту на основе предупреждений.

Авторизация

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

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

remove()

Снимает защиту диапазона или листа.

// Remove all range protections in the spreadsheet that the user has permission to edit.
var ss = SpreadsheetApp.getActive();
var protections = ss.getProtections(SpreadsheetApp.ProtectionType.RANGE);
for (var i = 0; i < protections.length; i++) {
  var protection = protections[i];
  if (protection.canEdit()) {
    protection.remove();
  }
}
// Remove sheet protection from the active sheet, if the user has permission to edit it.
var sheet = SpreadsheetApp.getActiveSheet();
var protection = sheet.getProtections(SpreadsheetApp.ProtectionType.SHEET)[0];
if (protection && protection.canEdit()) {
  protection.remove();
}

Авторизация

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

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

removeEditor(emailAddress)

Удаляет данного пользователя из списка редакторов защищенного листа или диапазона. Обратите внимание: если пользователь является членом группы Google, имеющей разрешение на редактирование, или если все пользователи в домене имеют разрешение на редактирование, пользователь по-прежнему сможет редактировать защищенную область. Ни владельца таблицы, ни текущего пользователя удалить нельзя.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Gets a sheet by its name.
const sheet = ss.getSheetByName('Sheet1');

// Creates a variable for an email address.
// TODO(developer): Replace the email address with a valid one.
const TEST_EMAIL = 'baklavainthebalkans@gmail.com';

// Protects the sheet.
const sampleProtectedSheet = sheet.protect();

// Adds an editor to the protected sheet using the email address variable.
sampleProtectedSheet.addEditor(TEST_EMAIL);

// Removes the editor from the protected sheet using the email address variable.
sampleProtectedSheet.removeEditor(TEST_EMAIL);

// Gets the editors of the protected sheet.
const editors = sampleProtectedSheet.getEditors();

// Logs the editors' email addresses to the console.
for (const editor of editors) {
  console.log(editor.getEmail());
}

Параметры

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

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

Protection — объект, представляющий настройки защиты для цепочки.

Авторизация

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

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

removeEditor(user)

Удаляет данного пользователя из списка редакторов защищенного листа или диапазона. Обратите внимание: если пользователь является членом группы Google, имеющей разрешение на редактирование, или если все пользователи в домене имеют разрешение на редактирование, он по-прежнему сможет редактировать защищенную область. Ни владельца таблицы, ни текущего пользователя удалить нельзя.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Gets a sheet by its name.
const sheet = ss.getSheetByName('Sheet1');

// Protects the sheet.
const sampleProtectedSheet = sheet.protect();

// Removes the active user from the editors of the protected sheet.
sampleProtectedSheet.removeEditor(Session.getActiveUser());

// Gets the editors of the protected sheet.
const editors = sampleProtectedSheet.getEditors();

// Logs the editors' email addresses to the console.
for (const editor of editors) {
  console.log(editor.getEmail());
}

Параметры

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

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

Protection — объект, представляющий настройки защиты, для цепочки

Авторизация

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

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

removeEditors(emailAddresses)

Удаляет заданный массив пользователей из списка редакторов защищенного листа или диапазона. Обратите внимание: если кто-либо из пользователей является членом группы Google, имеющей разрешение на редактирование, или если все пользователи в домене имеют разрешение на редактирование, эти пользователи по-прежнему смогут редактировать защищенную область. Ни владельца таблицы, ни текущего пользователя удалить нельзя.

// Protect the active sheet, then remove all other users from the list of editors.
var sheet = SpreadsheetApp.getActiveSheet();
var protection = sheet.protect().setDescription('Sample protected sheet');

// Ensure the current user is an editor before removing others. Otherwise, if the user's edit
// permission comes from a group, the script throws an exception upon removing the group.
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
  protection.setDomainEdit(false);
}

Параметры

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

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

Protection — объект, представляющий настройки защиты, для цепочки

Авторизация

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

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

removeTargetAudience(audienceId)

Удаляет указанную целевую аудиторию в качестве редактора защищенного диапазона.

Параметры

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

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

Protection — объект, представляющий настройки защиты для цепочки.

Авторизация

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

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

setDescription(description)

Задает описание защищенного диапазона или листа.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Gets the sheet 'Sheet1' by its name.
const sheet = ss.getSheetByName('Sheet1');

// Protects the sheet.
const sampleProtectedSheet = sheet.protect();

// Sets the sheet description to 'Sheet1 is protected.'
sampleProtectedSheet.setDescription('Sheet1 is protected');

// Gets the description of the protected sheet.
const sampleProtectedSheetDescription = sampleProtectedSheet.getDescription();

// Logs the description of the protected sheet to the console.
console.log(sampleProtectedSheetDescription);

Параметры

Имя Тип Описание
description String Описание защищенного диапазона или листа.

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

Protection — объект, представляющий настройки защиты для цепочки.

Авторизация

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

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

setDomainEdit(editable)

Определяет, имеют ли все пользователи домена, которому принадлежит электронная таблица, разрешение на редактирование защищенного диапазона или листа. Обратите внимание, что любые пользователи, имеющие явное разрешение на редактирование, могут редактировать защищенную область независимо от этого параметра. Выдает исключение, если электронная таблица не принадлежит домену Google Workspace (то есть если она принадлежит учетной записи gmail.com).

Параметры

Имя Тип Описание
editable Boolean true , если все пользователи в домене, которому принадлежит электронная таблица, должны иметь разрешение на редактирование защищенного диапазона или листа; false если нет.

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

Protection — объект, представляющий настройки защиты, для цепочки

Авторизация

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

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

setNamedRange(namedRange)

Связывает защищенный диапазон с существующим именованным диапазоном. Если именованный диапазон охватывает область, отличную от текущего защищенного диапазона, этот метод перемещает защиту, чтобы вместо этого охватить именованный диапазон. Именованный диапазон должен находиться на том же листе, что и текущий защищенный диапазон. Обратите внимание, что сценарии должны явно вызывать этот метод, чтобы связать защищенный диапазон с именованным диапазоном; вызова Range.protect() для создания защиты из Range , который является именованным диапазоном, без вызова setRangeName(rangeName) недостаточно для их связывания. Однако создание защищенного диапазона из именованного диапазона в пользовательском интерфейсе Google Sheets автоматически связывает их.

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Protects cells A1:D10 on Sheet1.
const sheet = ss.getSheetByName('Sheet1');
const protectedRange = sheet.getRange('A1:D10').protect();

// Logs the current protected range, A1:D10.
console.log(protectedRange.getRange().getA1Notation());

// Creates a named range for cells E1:J10 called 'NewRange.'
const newRange = sheet.getRange('E1:J10');
ss.setNamedRange('NewRange', newRange);
const namedRange = ss.getNamedRanges()[0];

// Updates the protected range to the named range, 'NewRange.'
// This updates the protected range on Sheet1 from A1:D10 to E1:J10.
protectedRange.setNamedRange(namedRange);

// Logs the updated protected range to the console.
console.log(protectedRange.getRange().getA1Notation());

Параметры

Имя Тип Описание
namedRange NamedRange Существующий именованный диапазон, который необходимо связать с защищенным диапазоном.

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

Protection — объект, представляющий настройки защиты для цепочки.

Авторизация

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

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

setRange(range)

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

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Protects cells A1:D10 on Sheet1 of the spreadsheet.
const sheet = ss.getSheetByName('Sheet1');
const protectedRange = sheet.getRange('A1:D10').protect();

// Logs the original protected range, A1:D10, to the console.
console.log(protectedRange.getRange().getA1Notation());

// Gets the range E1:J10.
const newRange = sheet.getRange('E1:J10');

// Updates the protected range to E1:J10.
protectedRange.setRange(newRange);

// Logs the updated protected range to the console.
console.log(protectedRange.getRange().getA1Notation());

Параметры

Имя Тип Описание
range Range Новый ассортимент для защиты от правок.

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

Protection — объект, представляющий настройки защиты для цепочки.

Авторизация

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

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

setRangeName(rangeName)

Связывает защищенный диапазон с существующим именованным диапазоном. Если именованный диапазон охватывает область, отличную от текущего защищенного диапазона, этот метод перемещает защиту, чтобы вместо этого охватить именованный диапазон. Именованный диапазон должен находиться на том же листе, что и текущий защищенный диапазон. Обратите внимание, что сценарии должны явно вызывать этот метод, чтобы связать защищенный диапазон с именованным диапазоном; вызова Range.protect() для создания защиты из Range , который является именованным диапазоном, без вызова setRangeName(rangeName) недостаточно для их связывания. Однако создание защищенного диапазона из именованного диапазона в пользовательском интерфейсе Google Sheets автоматически связывает их.

// Protect a named range in a spreadsheet and log the name of the protected range.
var ss = SpreadsheetApp.getActive();
var range = ss.getRange('A1:B10');
var protection = range.protect();
ss.setNamedRange('Test', range);       // Create a named range.
protection.setRangeName('Test');       // Associate the protection with the named range.
Logger.log(protection.getRangeName()); // Verify the name of the protected range.

Параметры

Имя Тип Описание
rangeName String Имя именованного диапазона, который необходимо защитить.

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

Protection — объект, представляющий настройки защиты, для цепочки

Авторизация

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

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

setUnprotectedRanges(ranges)

Снимает защиту с данного массива диапазонов внутри защищенного листа. Выдает исключение, если объект Protection соответствует защищенному диапазону, а не защищенному листу, или если какой-либо из диапазонов не находится на защищенном листе. Чтобы изменить незащищенные диапазоны, установите новый массив диапазонов; чтобы повторно защитить весь лист, установите пустой массив.

// Protect the active sheet except B2:C5, then remove all other users from the list of editors.
var sheet = SpreadsheetApp.getActiveSheet();
var protection = sheet.protect().setDescription('Sample protected sheet');
var unprotected = sheet.getRange('B2:C5');
protection.setUnprotectedRanges([unprotected]);

// Ensure the current user is an editor before removing others. Otherwise, if the user's edit
// permission comes from a group, the script throws an exception upon removing the group.
var me = Session.getEffectiveUser();
protection.addEditor(me);
protection.removeEditors(protection.getEditors());
if (protection.canDomainEdit()) {
  protection.setDomainEdit(false);
}

Параметры

Имя Тип Описание
ranges Range[] Массив диапазонов, которые следует оставить незащищенными на защищенном листе.

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

Protection — объект, представляющий настройки защиты, для цепочки

Авторизация

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

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

setWarningOnly(warningOnly)

Устанавливает, использует ли этот защищенный диапазон защиту «на основе предупреждений». Защита на основе предупреждений означает, что каждый пользователь может редактировать данные в области, за исключением того, что при редактировании отображается предупреждение с просьбой подтвердить редактирование. По умолчанию защищенные диапазоны или листы не основаны на предупреждениях. Чтобы проверить состояние предупреждения, используйте isWarningOnly() .

// Opens the spreadsheet file by its URL. If you created your script from within
// a Google Sheets file, you can use SpreadsheetApp.getActiveSpreadsheet() instead.
// TODO(developer): Replace the URL with your own.
const ss = SpreadsheetApp.openByUrl('https://docs.google.com/spreadsheets/d/abc123456/edit');

// Gets the sheet 'Sheet1' by its name.
const sheet = ss.getSheetByName('Sheet1');

// Protects the sheet and sets the protection to warning-based.
const sampleProtectedSheet = sheet.protect().setWarningOnly(true);

// Logs whether the protected sheet is warning-based to the console.
console.log(sampleProtectedSheet.isWarningOnly());

Параметры

Имя Тип Описание
warningOnly Boolean

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

Protection — объект, представляющий настройки защиты для цепочки.

Авторизация

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

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