Add listener while editing a text or note annotation

Q: How can I add an event listener while text is being edited into a text or note annotation?

A: You can add an annotations.willChange event listener to get notified when the content editable DOM node is mounted and then, attach a proper event listener to it.

Copy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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.