Search code examples
google-apps-scriptinsertgoogle-docsbookmarks

Is it possible to insert a Bookmark in Google Docs to a Table Cell/Table/Text via Google Apps Script?


Is it possible to insert a Bookmark at a table cell or text in Google Docs using Google Apps Script by e.g. specifying the table cell? From the documentation I understand that you need the absolute position which is bound to the cursor. What if I want to set Bookmarks at specified tables automatically. Is that not possible? Here the URL of the documentation: https://developers.google.com/apps-script/reference/document/bookmark

And if so is it possible to link the inserted bookmark with a table cell using Google Apps Script?


Solution

  • To add a bookmark without using cursors, you can do it via Position class. Since getCursor returns Position, we need to find other methods that returns the same, and that is newPosition which only requires the element and offset (if needed). See code below:

    Sample:

    sample

    Script:

    function myFunction() {
      var doc = DocumentApp.getActiveDocument();
      var body = doc.getBody();
      // find the text element
      var textElement = body.findText("<HERE>").getElement();
      // create position using the element
      var position = doc.newPosition(textElement, 0)
      // addBookmark using the created position
      doc.addBookmark(position);
    }
    

    Output:

    output

    Note:

    • For other objects, it should be doable as long as you can get the element and use it to get their positions.

    Reference: