Search code examples
google-apps-scriptgoogle-docs

How to Bookmark selection


I want to program the same functionality from Insert>Bookmark on Google Docs. I already used the addBookmark(cursor), now I want to do it on a selected text/image. See screenshot for reference ("congue" is the selected word).

enter image description here

enter image description here


Solution

  • You can add a bookmark at the selection using this as an example.

    function addBookmark() {
      try {
        let doc = DocumentApp.getActiveDocument();
        let selection = doc.getSelection();
        if( selection ) {
          let elements = selection.getRangeElements();
          let element = elements[0];
          let position = element.getStartOffset();
          position = doc.newPosition(element.getElement(),position);
          doc.addBookmark(position);
        }
      }
      catch(err) {
        console.log(err);
      }
    }
    

    Reference