Oleksandr
Oleksandr

Reputation: 25

Unable to clear footer from Google Document

When I run the code below, I receive a TypeError:

TypeError: Cannot call method "clear" of null. (line 3, file "Code")

from the line: footer.clear()

function insertFooterDate() {
  var footer = DocumentApp.getActiveDocument().getFooter();
  footer.clear();  // Line 3 - gets the footer & clears all data in footer. 

  //Get date
  var date = new Date();
  var month = date.getMonth()+1;
  var day = date.getDate();
  var year = date.getFullYear();
  var hour = date.getHours()+1;
  var minute = date.getMinutes()+1;
  var filename = doc.getName();

  footer.appendParagraph(day + '/' + month + '/' + year + ' ' + filename);  
  //adds date to footer with filename
}

Why do I get this error when my code executes?

Upvotes: 0

Views: 162

Answers (1)

tehhowch
tehhowch

Reputation: 9862

If there is no footer in a Google Docs file, you cannot call methods on that which does not exist. The Apps Script Document Service provides a method to add a footer, so you should make the decision to either abort your methods that require a footer if there is not one already, or create one. The decision will depend on what your methods are supposed to do.

function doStuffWithFooter_(myGDoc) {
  if (!myGDoc) return;
  const footer = myGDoc.getFooter();
  if (!footer) {
    console.warn("Document '" + myGDoc.getId() + "' had no footer.");
    return;
  }
  ... // code that should only run if the doc already had a footer
}

function addDateToFooter_(myGDoc) {
  if (!myGDoc) return;
  var footer = myGDoc.getFooter();
  if (!footer) {
    // no footer, so create one.
    footer = myGDoc.addFooter();
    console.log("Created footer for document '" + myGDoc.getId() + "'.");
  }
  ... // do stuff with footer, because we made sure one exists.
}

Upvotes: 1

Related Questions