Google Docs App Scripts
Jump to navigation
Jump to search
About
NOTE: This page is a daughter page of: Google Docs
The Google Docs App Script feature allows you to format your Google Docs with simple JavaScript code. Think of it like a word macro.
Child Pages
Related/Child Pages:
- Google Docs - Creating an Add On - This script inserts the date and a list of team members in random order - suitable for meeting notes where every person gets a chance to update the team on progress. We use this at Google.
- Google Docs - Format Matching Text Script - Will format any text lines starting with ±, but can be customized to other text.
How To: To Create a "Hello World" Add On via App Scripts
The right API to help is the Google Docs API... but that's slow to process, so here's what you need to do to create a new menu item that does something:
- Create a brand new Google Doc ............... (tip: Try typing into Chrome: docs.new)
- Click menu bar: Extensions > App Scripts.
- Enter the javascript code below into the Script Editor and hit "Save" and "Deploy" (as "Editor Add-On")
..... (tip: You can hit the play button to test one of the functions before saving) - Reload your Google Doc and approve permissions.
- Run the Script by clicking the new menu item that appears: Hello World > Hello.
(see pictures of this process)
Here's the code to add.
Code.gs
/**
* @fileoverview Hello world for Google Docs API.
* Instrutions and documentation for the script lives at:
* http://andrewnoske.com/wiki/Google_Docs_App_Scripts
*/
/**
* Called when doc opens. Creates menu iteams.
*/
function onOpen() {
DocumentApp.getUi().createMenu('Hello World')
.addItem('Hello', 'helloWorld') // Add a menu item tied to function below.
.addToUi();
}
/**
* Callback function.
*/
function helloWorld() {
var doc = DocumentApp.getActiveDocument();
var cursor = doc.getCursor();
var body = doc.getBody();
var offset = body.getChildIndex(cursor.getElement());
if (cursor) {
// More commands: https://developers.google.com/apps-script/reference/document/body
body.insertParagraph(offset, "Hello World");
} else {
DocumentApp.getUi().alert('Cannot find a cursor in the document.');
}
}
Links
- Google Docs API - About the API.