简体   繁体   中英

Apps Script - Bookmark a Date Element on Google Docs

In general, I want to recreate the Insert>Bookmark on Google docs with a custom function upon bookmarking an element (all types of elements).

Now my issue is on bookmarking the Date element. I am getting

TypeError: Cannot read property 'getRangeElements' of null

在此处输入图像描述

My current code for bookmarking Date element was something like this


selection.getRangeElements().forEach(e => {
  const elmnt = e.getElement();
  const type = elmnt.getType();

  if( type == DocumentApp.ElementType.DATE ){
    bookmarked = doc.addBookmark( doc.newPosition(elmnt.asDate().getParent(), 1) )
  }

}); ```

Modification points:

  • When I saw your showing script and your error message of TypeError: Cannot read property 'getRangeElements' of null , if selection is DocumentApp.getActiveDocument().getSelection() , I'm worried that you might have run the script without selecting the smart chip of Date. Please confirm this again.
  • And, in your script, ele is not declared. So, even when the error of TypeError: Cannot read property 'getRangeElements' of null was resolved, an error occurs at const type = ele.getType(); .

When these points are reflected in your script, it becomes as follows.

Modified script:

When you run this script, please select the smart chip of Date and run the script. By this, the smart chip of Date is added as the bookmark.

function myFunction() {
  const doc = DocumentApp.getActiveDocument();
  const selection = doc.getSelection();
  selection.getRangeElements().forEach(e => {
    const ele = e.getElement();
    const type = ele.getType();
    if (type == DocumentApp.ElementType.DATE) {
      bookmarked = doc.addBookmark(doc.newPosition(ele.asDate().getParent(), 1));
    }
  });
}

Reference:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM