Skip to content

Instantly share code, notes, and snippets.

@bluprince13
Last active January 17, 2023 18:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bluprince13/b895d6d5d187e7a0fe0da75bfeb9f3db to your computer and use it in GitHub Desktop.
Save bluprince13/b895d6d5d187e7a0fe0da75bfeb9f3db to your computer and use it in GitHub Desktop.
Make Google Docs file read only / lock / protect
// 1. Open your document on Google.
// 2. Go to Tools > Script Editor.
// 3. Copy the following script and save the script.
// 4. Go back to the document.
// 5. Go to the new Custom menu > Make file read only
// 6. To unlock, there will be an Unlock button on the UI (provided by Google)
//
// Inspired by https://www.labnol.org/code/read-only-google-drive-file-201011
const makeGoogleDocFileReadyOnly = () => {
const fileId = DocumentApp.getActiveDocument().getId();
UrlFetchApp.fetch(`https://www.googleapis.com/drive/v3/files/${fileId}`, {
method: 'PATCH',
contentType: 'application/json',
headers: {
Authorization: `Bearer ${ScriptApp.getOAuthToken()}`,
},
payload: JSON.stringify({
contentRestrictions: [
{
readOnly: true,
reason: 'Prevent accidental editing',
},
],
}),
});
};
function onOpen() {
var ui = DocumentApp.getUi();
ui.createMenu('Custom Menu')
.addItem('Make file read only', 'makeFileReadyOnlyMenuItem')
.addToUi();
}
function makeFileReadyOnlyMenuItem() {
makeGoogleDocFileReadyOnly()
DocumentApp.getUi()
.alert('You clicked the first menu item!');
}
@thanhtam23
Copy link

do I need to run the script? there is error by the way

TypeError: Cannot read properties of null (reading 'getId')

@bluprince13
Copy link
Author

@thanhtam23 Step 5 of the instructions (top of file) is where you run the script , i.e., by clicking the menu item.

It works fine for me.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment