Home > Blockchain >  How do I use Google Apps Script to delete everything in a google document via a function?
How do I use Google Apps Script to delete everything in a google document via a function?

Time:11-18

I'm trying to make a function on google docs to purge the document, (deleting everything in the document, and here's what I have so far:

function onOpen() {
  let ui = DocumentApp.getUi();
  ui.createMenu('Extras')
  .addItem('Purge Document', 'myFunction')
  .addToUi();
};

function myFunction() {
    var ui = DocumentApp.getUi();

  var result = ui.alert(
     'Purge?',
     'Are you sure you want to purge the document? It will delete EVERYTHING. This is irreversible.',
      ui.ButtonSet.YES_NO);

  // responses
  if (result == ui.Button.YES) {
    // Clicked Yes ^^^
    ui.alert('Purging...');
  purge()
  } else {
    // User clicked No vvv
  }
}

function purge(doc){
  [heres where I need help]
     }

Can anybody help me? Thanks.

CodePudding user response:

Probably something like this will do the work:

function purge() {
  var doc = DocumentApp.getActiveDocument()
  try { doc.getBody().clear()   } catch(e) {}
  try { doc.getFooter().clear() } catch(e) {}
  try { doc.getHeader().clear() } catch(e) {}
}

The code for Spreadsheet, just in case:

function purge() {
  SpreadsheetApp.getActiveSpreadsheet().getSheets().forEach(s => s.clear());
}
  • Related