In this tutorial, we will see how we can add a custom menu and submenu in Google Docs (Spreadsheet, Document, etc.) and then add some action when the menu or submenu is clicked.
This solution is for the following problem I had:
I had a lot of programming code blocks in a Google Document.
I wanted to format the code blocks.
For example:
– Change the font family to “Courier New”,
– decrease the font size,
– and add a background color to the code blocks.
Here, I am using Google Document to add the menu and menu action.
Here are the steps to follow:
PS: You can also add the menu in Google Spreadsheet by following the below steps.
- Open Google Documents.
- Go to Tools -> Script Editor
- A new tab/window opens where you can write the appscript code
- Write the following code in the editor:
function onOpen(e) {
var ui = DocumentApp.getUi();
ui.createMenu('Custom')
.addItem('Code', 'codeBlock')
.addItem('New Menu', 'getRange')
.addSeparator()
.addSubMenu(
ui.createMenu('Advanced')
.addItem('New Submenu', 'getRangeValues')
)
.addToUi();
ui.createMenu('Code', 'myFunction')
.addToUi();
}
function codeBlock() {
const selection = DocumentApp.getActiveDocument().getSelection();
selection.getRangeElements().forEach((element)=>{
element
.getElement()
.asText()
.setFontFamily("Courier New")
.setFontSize(10)
.setBackgroundColor("#f3f3f3");
})
}
- Save the code (File -> Save) or by typing CTRL+S or CMD+S
-
Click on the Run button
-
This will ask for permission
-
Click on “Review Permissions” button
-
This will open a popup window with the Gmail login page or with your gmail account name if you are already logged in
-
Click on the gmail account name
-
Then it shall show the following message:
Google hasn’t verified this app
The app is requesting access to sensitive info in your Google Account. Until the developer (your.name@gmail.com) verifies this app with Google, you shouldn’t use it.Advanced
-
Click on the “Advanced” link
-
Then it will show the following message
Continue only if you understand the risks and trust the developer (your.name@gmail.com).
Go to Code (unsafe)
-
Click on “Go to Code (unsafe)“
-
This will show message asking to allow access for the code
Code wants to access your Google Account
-
Click on the “Allow Access” button
-
Now, on your Google Document, you should be able to see the newly created custom menu.
Custom
– Code
– New Menu
– Advanced
– New Submenu
Now, when you select any text in the Google Document and then select Custom -> Code menu, then it will change the selected font size, font family, and background color.
Hope this helps. Thanks.