edit google document remotely

2019-05-14 11:04发布

问题:

I'm trying to add a feature to my website as follows:

Clicking a button appends text to a Google document.

Obviously I will need to create an Apps Script in the drive. The question is how to trigger the Apps Script from my website. You can assume that I am the owner of the drive/document and so have permissions to edit it in any way I like.

I have looked at these topics:

  1. Workarounds : How to edit native google documents programatcally?item
  2. How to programmatically manipulate native google doc files

It seems they are all actions performed from the drive itself and not triggered remotely.

I have also looked up the Apps Script API in Google but have not found a way to do this. Is it even possible?

回答1:

Yes, it is possible.

First write an Apps script that changes your desired document. Then deploy it as a web-app running as you that anyone has access, even anonymous. Check out the guides at Apps Script page to see how to write your script as a web-app.

Your script will then have a public url, which you can call from your website and have it run "remotely" normally.



回答2:

To provide an example of what Henrique suggests, here is a small webapp that adds text to a publicly viewable document I own (it doesn't need to be public except for anyone here to check it works !)

I wrote it using UiApp but you could of course use HTMLService if you prefer...

The app runs as me but is accessible to anyone even anonymous.

// publicly viewable test doc url : https://docs.google.com/document/d/1THzBTURxGr2CdUmcZ7i2zD-RM8I3im2JCSHI3BHlkeM/edit

function doGet(){
  var app = UiApp.createApplication().setTitle('docEdit');
  var panel = app.createAbsolutePanel().setSize('100%','100%').setStyleAttributes({'padding':'40px','backgroundColor':'lightBlue'});
  var text = app.createTextArea().setName('text').setPixelSize(500,300);
  var grid = app.createFlexTable().setId('grid');
  grid.setText(0,0,'Add your text').setWidget(1,0,text);  
  var handler = app.createServerHandler('writeText').addCallbackElement(panel);
  grid.setWidget(2,0,app.createButton('update document',handler).setId('btn'));
  app.add(panel.add(grid));
  return app;
}

function writeText(e){
  var doc = DocumentApp.openById('1THzBTURxGr2CdUmcZ7i2zD-RM8I3im2JCSHI3BHlkeM');
  var now = Utilities.formatDate(new Date(),Session.getScriptTimeZone(),'MMM/dd/yyyy @ hh:mm:ss');
  var body = doc.getBody();
  body.appendParagraph('Append text on '+now+' : '+e.parameter.text);
  doc.saveAndClose();
  var app = UiApp.getActiveApplication();
  var grid = app.getElementById('grid');
  grid.setWidget(3,0,app.createHTML('Thanks,<br>Your text has been added to the document'));
  app.getElementById('btn').setEnabled(false).setHTML('Button disabled');
  return app;
}