Edit

Share via


Work with events using the Word JavaScript API

This article describes important concepts related to working with events in Word and provides code samples that show how to register event handlers, handle events, and remove event handlers using the Word JavaScript API.

Events in Word

When certain changes occur in a Word document, event notifications fire. The Word JavaScript APIs let you register event handlers that allow your add-in to automatically run designated functions when those changes occur. The following events are currently supported.

Event Description Supported objects Triggered during coauthoring?
onAnnotationClicked Occurs when the user selects an annotation.

Event data object:
AnnotationClickedEventArgs
Document No
onAnnotationHovered Occurs when the user hovers the cursor over an annotation.

Event data object:
AnnotationHoveredEventArgs
Document No
onAnnotationInserted Occurs when the user adds one or more annotations.

Event data object:
AnnotationInsertedEventArgs
Document No
onAnnotationPopupAction Occurs when the user performs an action in an annotation pop-up menu.

Event data object:
AnnotationPopupActionEventArgs
Document No
onAnnotationRemoved Occurs when the user deletes one or more annotations.

Event data object:
AnnotationRemovedEventArgs
Document No
onContentControlAdded Occurs when a content control is added. Run context.sync() in the handler to get the new content control's properties.

Event data object:
ContentControlAddedEventArgs
Document Yes
onDataChanged Occurs when data within the content control are changed. To get the new text, load this content control in the handler. To get the old text, do not load it.

Event data object:
ContentControlDataChangedEventArgs
ContentControl Yes
onDeleted Occurs when the content control is deleted. Do not load this content control in the handler, otherwise you won't be able to get its original properties.

Event data object:
ContentControlDeletedEventArgs
ContentControl Yes
onEntered Occurs when the content control is entered.

Event data object:
ContentControlEnteredEventArgs
ContentControl Yes
onExited Occurs when the content control is exited, for example, when the cursor leaves the content control.

Event data object:
ContentControlExitedEventArgs
ContentControl Yes
onParagraphAdded Occurs when the user adds new paragraphs.

Event data object:
ParagraphAddedEventArgs
Document Yes
onParagraphChanged Occurs when the user changes paragraphs.

Event data object:
ParagraphChangedEventArgs
Document Yes
onParagraphDeleted Occurs when the user deletes paragraphs.

Event data object:
ParagraphDeletedEventArgs
Document Yes
onSelectionChanged Occurs when selection within the content control is changed.

Event data object:
ContentControlSelectionChangedEventArgs
ContentControl Yes

Events in preview

Note

The following events are currently available only in public preview. To use this feature, you must use the preview version of the Office JavaScript API library from the Office.js content delivery network (CDN). The type definition file for TypeScript compilation and IntelliSense is found at the CDN and DefinitelyTyped. You can install these types with npm install --save-dev @types/office-js-preview.

Event Description Supported objects Triggered during coauthoring?
onCommentAdded Occurs when new comments are added.

Event data object:
CommentEventArgs
Yes
onCommentChanged Occurs when a comment or its reply is changed.

Event data object:
CommentEventArgs
Yes
onCommentDeleted Occurs when comments are deleted.

Event data object:
CommentEventArgs
Yes
onCommentDeselected Occurs when a comment is deselected.

Event data object:
CommentEventArgs
Yes
onCommentSelected Occurs when a comment is selected.

Event data object:
CommentEventArgs
Yes

Event triggers

Events within a Word document can be triggered by:

  • User interaction via the Word user interface (UI) that changes the document.
  • Office Add-in (JavaScript) code that changes the document.
  • VBA add-in (macro) code that changes the document.
  • A coauthor who remotely changes the document using the Word UI or add-in code. For more information, see Events and coauthoring.

Any change that complies with default behavior of Word will trigger the corresponding events in a document.

Lifecycle of an event handler

An event handler is created when an add-in registers the event handler. It's destroyed when the add-in deregisters the event handler or when the add-in is refreshed, reloaded, or closed. Event handlers don't persist as part of the Word file, or across sessions with Word on the web.

Events and coauthoring

With coauthoring, multiple people can work together and edit the same Word document simultaneously. For events that can be triggered by a coauthor, such as onParagraphChanged, the corresponding Event object will contain a source property that indicates whether the event was triggered locally by the current user (event.source == Local) or was triggered by the remote coauthor (event.source == Remote).

Events that use the following data objects are triggered during coauthoring.

  • CommentEventArgs (preview)
  • ContentControlAddedEventArgs
  • ContentControlDataChangedEventArgs
  • ContentControlDeletedEventArgs
  • ContentControlEnteredEventArgs
  • ContentControlExitedEventArgs
  • ContentControlSelectionChangedEventArgs
  • ParagraphAddedEventArgs
  • ParagraphChangedEventArgs
  • ParagraphDeletedEventArgs

Register an event handler

The following code sample registers an event handler for the onParagraphChanged event in the document. The code specifies that when content changes in the document, the handleChange function runs.

await Word.run(async (context) => {
    eventContext = context.document.onParagraphChanged.add(handleChange);

    await context.sync();
    console.log("Event handler successfully registered for onParagraphChanged event in the document.");
}).catch(errorHandlerFunction);

As shown in the previous example, when you register an event handler, you indicate the function that should run when the specified event occurs. You can design that function to perform whatever actions your scenario requires. The following code sample shows an event handler function that simply writes information about the event to the console.

async function handleChange(event) {
    await Word.run(async (context) => {
        await context.sync();        
        console.log("Type of event: " + event.type);
        console.log("Source of event: " + event.source);       
    }).catch(errorHandlerFunction);
}

Remove an event handler

The following code sample registers an event handler for the onParagraphChanged event in the document and defines the handleChange function that will run when the event occurs. It also defines the deregisterEventHandler() function that can subsequently be called to remove that event handler. Note that the RequestContext used to create the event handler is needed to remove it.

let eventContext;

async function registerEventHandler() {
  await Word.run(async (context) => {
    eventContext = context.document.onParagraphChanged.add(handleChange);

    await context.sync();
    console.log("Event handler successfully registered for onParagraphChanged event in the document.");
  });
}

async function handleChange(event: Word.ParagraphChangedEventArgs) {
  await Word.run(async (context) => {
    await context.sync();
    console.log(`${event.type} event was detected.`);
  });
}

async function deregisterEventHandler() {
  // The `RequestContext` used to create the event handler is needed to remove it.
  // In this example, `eventContext` is being used to keep track of that context.
  await Word.run(eventContext.context, async (context) => {
    eventContext.remove();
    await context.sync();
    
    eventContext = null;
    console.log("Removed event handler that was tracking content changes in paragraphs.");
  });
}

Use .track()

Certain event types also require you to call track() on the object you're adding the event to.

  • Content control events
    • onDataChanged
    • onDeleted
    • onEntered
    • onExited
    • onSelectionChanged
  • Comment events (preview)
    • onCommentAdded
    • onCommentChanged
    • onCommentDeleted
    • onCommentDeselected
    • onCommentSelected

The following code sample shows how to register an event handler on each content control. Because you're adding the event to the content controls, track() is called on each content control in the collection.

let eventContexts = [];

await Word.run(async (context) => {
  const contentControls: Word.ContentControlCollection = context.document.contentControls;
  contentControls.load("items");
  await context.sync();

  // Register the onDeleted event handler on each content control.
  if (contentControls.items.length === 0) {
    console.log("There aren't any content controls in this document so can't register event handlers.");
  } else {
    for (let i = 0; i < contentControls.items.length; i++) {
      eventContexts[i] = contentControls.items[i].onDeleted.add(contentControlDeleted);

      // Call track() on each content control.
      contentControls.items[i].track();
    }

    await context.sync();

    console.log("Added event handlers for when content controls are deleted.");
  }
});

The following code sample shows how to register comment event handlers on the document's body object and includes a body.track() call.

let eventContexts = [];

// Registers event handlers.
await Word.run(async (context) => {
  const body: Word.Body = context.document.body;

  // Track the body object since you're adding comment events to it.
  body.track();
  await context.sync();

  eventContexts[0] = body.onCommentAdded.add(onEventHandler);
  eventContexts[1] = body.onCommentChanged.add(onChangedHandler);
  eventContexts[2] = body.onCommentDeleted.add(onEventHandler);
  eventContexts[3] = body.onCommentDeselected.add(onEventHandler);
  eventContexts[4] = body.onCommentSelected.add(onEventHandler);
  await context.sync();

  console.log("Event handlers registered.");
});

See also