简体   繁体   中英

How to install Google App Script into Google docs that can be used on my own document?

The Interface and documentation for the Google Apps script is not very good there is lot of things and I'm not able to find anything useful in google search. I've created my own cloud project and my own google script project connected them using my permission screen and project. I've created code that works I've created trigger open but I have no idea what to do next how to add it to my document, so I can actually use my script on the document instead of the editor.

I need to create script that will be used by everyone that open my document in my organization.

My code looks like this:

function toggleBorders() {
  var doc = DocumentApp.getActiveDocument();
  var body = doc.getBody();
  var tables = body.getTables();
  var black = '#000000';
  var white = '#ffffff';
  tables.forEach(function(table) {
    var color = table.getBorderColor();
    table.setBorderColor(color == black ? white : black);
  })
}

function onOpen() {
  var ui = DocumentApp.getUi();
  var menu = ui.createMenu('JJ Scripts').addItem('Toogle Borders', 'toggleBorders');
  menu.addToUi();
}

I've not even able to run onOpen from editor because got error:

Cannot call DocumentApp.getUi() from this context

Is there a way to install Google App Script into my own document so I can actually use it outside of editor?

1. possibility: Your code is not bound

  • The method DocumentApp.getUi() is only available for bound scripts
  • If not already done - bind the script to the document of your choice by going on Tools -> Script Editor , pasting adn saving the code
  • Run onOpen() once manually to give the script the necessary permissions

2. possibility: your code is bound to a non Google-Docs document

  • The DocumentApp UI can only be called from a Google Docs document
  • If your script is bound to eg a Google spreadsheet, DocumentApp.getUi() will fail, you need to use SpreadsheetApp.getUi() instead (and rewrite toggleBorders() )

3. possibility: you want to make the code universal, without having to bind it to a document

  • In this case you need to create a GSuite Addon and install it, so that the code works for each of your documents

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM