Google Docs App Scripts

From NoskeWiki
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:


What you can do


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:

  1. Create a brand new Google Doc ............... (tip: Try typing into Chrome: docs.new)
  2. Click menu bar: Extensions > App Scripts.
  3. 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)
  4. Reload your Google Doc and approve permissions.
  5. 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.');
  }
}



Working on a script
Working on a script
Permissions step


Links