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.
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.