I saw some examples, but I could not understand how they work and how to add the script to be launched on Google Doc. I would like to be able to launch the script of a personal function, without having to enter the editor and click run. As it will be shared with colleagues, I would like to avoid that by mistake they delete the data from the script. Are there any alternatives? It would be to put the startup in the sidebar or in the menu. And also an explanation of how the operation takes place, and how to connect the script.
If you want a sidebar it can be done this way:
Make two files in Script Editor: 'Code.gs' and 'sidebar.html'
Code.gs
function onOpen() {
DocumentApp.getUi().createMenu('🛠️ Scripts')
.addItem('Show sidebar', 'launchSideBar')
.addToUi()
}
function launchSideBar() {
DocumentApp.getUi().showSidebar(HtmlService.createHtmlOutputFromFile('sidebar').setTitle('Sidebar Title'))
}
function hello() {
DocumentApp.getUi().alert('Hello!'); // just an example, you can put your code here
}
sidebar.html
<!DOCTYPE html>
<html>
<head>
<base target="_top">
</head>
<body>
<input type="button" value="Hello" onClick="google.script.run.hello();" />
</body>
</html>
After reload the document it will give the menu 'Scripts' and command 'Show sidebar'
After click on the command it will show the sidebar with the button 'Hello'
Button Hello
will run the function hello()
.
Update
But actually, since you have to make a custom menu to show the sidebar anyway, it makes sense don't use a sidebar at all and use a custom menu only.
In this case you don't need the file 'sidebar.html' and your 'Code.gs' will look like this:
function onOpen() {
DocumentApp.getUi().createMenu('🛠️ Scripts')
.addItem('Hello', 'hello')
.addItem('Bye-bye', 'bye')
.addToUi()
}
function hello() {
// just an example, you can put any code here
DocumentApp.getUi().alert('Hello!');
}
function bye() {
// just an example, you can put any code here
DocumentApp.getUi().alert('Bye!');
}
// etc
It will get you the menu 'Scripts' with the commands 'Hello' and 'Bye-bye' that run the functions hello()
and bye()
respectively.