How to log an object in Google Apps Script?

Viewed 678

I'm new to Google Apps Script (I'm developing an add-on for Google Docs) and have trouble logging objects for debugging purposes.

For example, when I try to get the following information and log it

let x = DocumentApp.getActiveDocument().getSelection();
Logger.log(x);

the logger prints "Range". In other words, it seems to be printing the type of the object I'm trying to print, not a stringification of its keys and values (or whatever App Script objects are made of).

Instead, I would like to print that object's properties and the corresponding values.

According to the documentation, it looks as though the Logger only takes strings. Therefore, I have tried stringifying the objects I'm trying to log, using JSON.stringify, e.g. Logger.log(JSON.stringify(x));, but then it just prints "{}". That seems wrong, given that I have made sure to select something in the document. The same happens for getCursor() even though I have my cursor positioned in the document.

Stringifying the objects before logging them seemed like a step in the right direction, but... What am I doing wrong?

1 Answers

Most if not all inbuilt object's properties are not enumerable(See Enumerability and ownership of objects). You may be able to get most properties using a combination of Object.getOwnPropertyNames, Object.getOwnPropertySymbols. You can get all their flags(enumerable,configurable, etc) using Object.getOwnPropertyDescriptors

//@OnlyCurrentDoc
const getAllSelectionNames = () => {
  'use strict';
  const getObjNamesAndValues = x =>
    Object.getOwnPropertyNames(x).map(k => ({ [k]: x[k] }));
  const x = DocumentApp.getActiveDocument().getSelection();
  if (x) console.log(getObjNamesAndValues(x));
};
Related