Add a Listener While Editing a Text or Note Annotation

It’s possible to add an event listener while text is being edited in a text or note annotation. This is done by first adding an annotations.willChange event listener to get notified when the content editable DOM node is mounted, and then attaching a proper event listener to it:

PSPDFKit.load({
  // Your configuration.
}).then((instance) => {
  let inputListener = (e) => {
    console.log("Content changed: ", e.target.textContent);
  };

  instance.addEventListener("annotations.willChange", (e) => {
    if (
      e.reason ===
        PSPDFKit.AnnotationsWillChangeReason.TEXT_EDIT_START &&
      (e.annotations.first() instanceof
        PSPDFKit.Annotations.TextAnnotation ||
        e.annotations.first() instanceof
          PSPDFKit.Annotations.NoteAnnotation)
    ) {
      const inputEl = instance.contentDocument.querySelector(
        "[contenteditable='true']"
      );
      if (inputEl) {
        inputEl.addEventListener("input", inputListener);
      }
    } else if (
      e.reason === PSPDFKit.AnnotationsWillChangeReason.TEXT_EDIT_END &&
      (e.annotations.first() instanceof
        PSPDFKit.Annotations.TextAnnotation ||
        e.annotations.first() instanceof
          PSPDFKit.Annotations.NoteAnnotation)
    ) {
      const inputEl = instance.contentDocument.querySelector(
        "[contenteditable='true']"
      );
      if (inputEl) {
        inputEl.removeEventListener("input", inputListener);
      }
    }
  });
  return instance;
});

This has been tested with PSPDFKit for Web 2020.4.2.