Verwenden von Anmerkungen in Ihrem Word-Add-In

Umfasst Community-Beiträge von:Abdulhadi Jarad

Verwenden Sie Anmerkungen, um Feedback direkt in einem Word Dokument anzuzeigen, z. B. Grammatikanleitungen oder Verbesserungsvorschläge. Word markiert den betroffenen Text und kann ein Popup mit vorgeschlagenen Aktionen anzeigen, wenn der Benutzer auf die Anmerkung zeigt.

In diesem Artikel wird folgendes beschrieben:

  1. Registrieren Sie Anmerkungsereignisse , damit Ihr Add-In auf Benutzeraktionen reagieren kann.
  2. Fügen Sie dem aktuellen Absatz Kritiken hinzu.
  3. Untersuchen Des Anmerkungszustands und der Kritikdetails.
  4. Anwenden oder Verwerfen von Vorschlägen und Ablehnen einer Anmerkung.
  5. Entfernen Sie Anmerkungen , wenn Sie sie nicht mehr benötigen.

Wichtig

Diese Anmerkungen werden nicht im Dokument beibehalten. Dies bedeutet, dass die Anmerkungen neu generiert werden müssen, wenn das Dokument erneut geöffnet wird. Wenn der Benutzer jedoch vorgeschlagene Änderungen akzeptiert, bleiben die Änderungen bestehen, solange der Benutzer sie vor dem Schließen des Dokuments speichert.

Voraussetzungen

Die Anmerkungs-APIs basieren auf einem Dienst, der ein Microsoft 365-Abonnement erfordert. Daher funktioniert die Verwendung dieses Features in Word mit einer Lizenz für einmaligen Kauf nicht. Der Benutzer muss Word ausführen, der mit einem Microsoft 365-Abonnement verbunden ist, damit Ihr Add-In die Anmerkungs-APIs erfolgreich ausführen kann.

APIs für Schlüsselanmerkungen

Im Folgenden sind die wichtigsten Anmerkungs-APIs aufgeführt.

Verwenden von Anmerkungs-APIs

In den folgenden Abschnitten wird gezeigt, wie Sie mit Anmerkungs-APIs arbeiten. Die Beispiele basieren auf dem Codebeispiel Zum Verwalten von Anmerkungen.

Verwenden Sie die Feedback- oder Kritikergebnisse Ihres Diensts, um Anmerkungen dynamisch basierend auf dem Dokumentinhalt des Benutzers zu verwalten.

Registrieren von Anmerkungsereignissen

Der folgende Code zeigt, wie Ereignishandler registriert werden. Weitere Informationen zum Arbeiten mit Ereignissen in Word finden Sie unter Arbeiten mit Ereignissen mithilfe der Word JavaScript-API. Beispiele für Ereignishandler für Anmerkungen finden Sie in den folgenden Abschnitten.

let eventContexts = [];

async function registerEventHandlers() {
  // Registers event handlers.
  await Word.run(async (context) => {
    eventContexts[0] = context.document.onParagraphAdded.add(paragraphChanged);
    eventContexts[1] = context.document.onParagraphChanged.add(paragraphChanged);

    eventContexts[2] = context.document.onAnnotationClicked.add(onClickedHandler);
    eventContexts[3] = context.document.onAnnotationHovered.add(onHoveredHandler);
    eventContexts[4] = context.document.onAnnotationInserted.add(onInsertedHandler);
    eventContexts[5] = context.document.onAnnotationRemoved.add(onRemovedHandler);
    eventContexts[6] = context.document.onAnnotationPopupAction.add(onPopupActionHandler);

    await context.sync();

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

onClickedHandler-Ereignishandler

Der folgende Code wird ausgeführt, wenn das registrierte onAnnotationClicked Ereignis auftritt.

async function onClickedHandler(args: Word.AnnotationClickedEventArgs) {
  // Runs when the registered Document.onAnnotationClicked event occurs.
  await Word.run(async (context) => {
    const annotation: Word.Annotation = context.document.getAnnotationById(args.id);
    annotation.load("critiqueAnnotation");

    await context.sync();

    console.log(`AnnotationClicked: ID ${args.id}:`, annotation.critiqueAnnotation.critique);
  });
}

onHoveredHandler-Ereignishandler

Der folgende Code wird ausgeführt, wenn das registrierte onAnnotationHovered Ereignis auftritt.

async function onHoveredHandler(args: Word.AnnotationHoveredEventArgs) {
  // Runs when the registered Document.onAnnotationHovered event occurs.
  await Word.run(async (context) => {
    const annotation: Word.Annotation = context.document.getAnnotationById(args.id);
    annotation.load("critiqueAnnotation");

    await context.sync();

    console.log(`AnnotationHovered: ID ${args.id}:`, annotation.critiqueAnnotation.critique);
  });
}

onInsertedHandler-Ereignishandler

Der folgende Code wird ausgeführt, wenn das registrierte onAnnotationInserted Ereignis auftritt.

async function onInsertedHandler(args: Word.AnnotationInsertedEventArgs) {
  // Runs when the registered Document.onAnnotationInserted event occurs.
  await Word.run(async (context) => {
    const annotations = [];
    for (let i = 0; i < args.ids.length; i++) {
      let annotation: Word.Annotation = context.document.getAnnotationById(args.ids[i]);
      annotation.load("id,critiqueAnnotation");
      annotations.push(annotation);
    }

    await context.sync();

    for (let annotation of annotations) {
      console.log(`AnnotationInserted: ID ${annotation.id}:`, annotation.critiqueAnnotation.critique);
    }
  });
}

onRemovedHandler-Ereignishandler

Der folgende Code wird ausgeführt, wenn das registrierte onAnnotationRemoved Ereignis auftritt.

async function onRemovedHandler(args: Word.AnnotationRemovedEventArgs) {
  // Runs when the registered Document.onAnnotationRemoved event occurs.
  await Word.run(async (context) => {
    for (let id of args.ids) {
      console.log(`AnnotationRemoved: ID ${id}`);
    }
  });
}

onPopupActionHandler-Ereignishandler

Der folgende Code wird ausgeführt, wenn das registrierte onAnnotationPopupAction Ereignis auftritt.

async function onPopupActionHandler(args: Word.AnnotationPopupActionEventArgs) {
  // Runs when the registered Document.onAnnotationPopupAction event occurs.
  await Word.run(async (context) => {
    let message = `AnnotationPopupAction: ID ${args.id} = `;
    if (args.action === "Accept") {
      message += `Accepted: ${args.critiqueSuggestion}`;
    } else {
      message += "Rejected";
    }

    console.log(message);
  });
}

Anmerkungen einfügen

Der folgende Code zeigt, wie Anmerkungen in den ausgewählten Absatz eingefügt werden.

async function insertAnnotations() {
  // Adds annotations to the selected paragraph.
  await Word.run(async (context) => {
    const paragraph: Word.Paragraph = context.document.getSelection().paragraphs.getFirst();
    const options: Word.CritiquePopupOptions = {
      brandingTextResourceId: "PG.TabLabel",
      subtitleResourceId: "PG.HelpCommand.TipTitle",
      titleResourceId: "PG.HelpCommand.Label",
      suggestions: ["suggestion 1", "suggestion 2", "suggestion 3"]
    };
    const critique1: Word.Critique = {
      colorScheme: Word.CritiqueColorScheme.red,
      start: 1,
      length: 3,
      popupOptions: options
    };
    const critique2: Word.Critique = {
      colorScheme: Word.CritiqueColorScheme.green,
      start: 6,
      length: 1,
      popupOptions: options
    };
    const critique3: Word.Critique = {
      colorScheme: Word.CritiqueColorScheme.blue,
      start: 10,
      length: 3,
      popupOptions: options
    };
    const critique4: Word.Critique = {
      colorScheme: Word.CritiqueColorScheme.lavender,
      start: 14,
      length: 3,
      popupOptions: options
    };
    const critique5: Word.Critique = {
      colorScheme: Word.CritiqueColorScheme.berry,
      start: 18,
      length: 10,
      popupOptions: options
    };
    const annotationSet: Word.AnnotationSet = {
      critiques: [critique1, critique2, critique3, critique4, critique5]
    };

    const annotationIds = paragraph.insertAnnotations(annotationSet);

    await context.sync();

    console.log("Annotations inserted:", annotationIds.value);
  });
}

Abrufen von Anmerkungen

Der folgende Code zeigt, wie Anmerkungen aus dem ausgewählten Absatz abgerufen werden.

async function getAnnotations() {
  // Gets annotations found in the selected paragraph.
  await Word.run(async (context) => {
    const paragraph: Word.Paragraph = context.document.getSelection().paragraphs.getFirst();
    const annotations: Word.AnnotationCollection = paragraph.getAnnotations();
    annotations.load("id,state,critiqueAnnotation");

    await context.sync();

    console.log("Annotations found:");

    for (let i = 0; i < annotations.items.length; i++) {
      const annotation: Word.Annotation = annotations.items[i];

      console.log(`ID ${annotation.id} - state '${annotation.state}':`, annotation.critiqueAnnotation.critique);
    }
  });
}

Akzeptieren einer Anmerkung

Der folgende Code zeigt, wie sie die erste Anmerkung akzeptieren, die im ausgewählten Absatz gefunden wurde.

async function acceptFirst() {
  // Accepts the first annotation found in the selected paragraph.
  await Word.run(async (context) => {
    const paragraph: Word.Paragraph = context.document.getSelection().paragraphs.getFirst();
    const annotations: Word.AnnotationCollection = paragraph.getAnnotations();
    annotations.load("id,state,critiqueAnnotation");

    await context.sync();

    for (let i = 0; i < annotations.items.length; i++) {
      const annotation: Word.Annotation = annotations.items[i];

      if (annotation.state === Word.AnnotationState.created) {
        console.log(`Accepting ID ${annotation.id}...`);
        annotation.critiqueAnnotation.accept();

        await context.sync();
        break;
      }
    }
  });
}

Ablehnen einer Anmerkung

Der folgende Code zeigt, wie die letzte Im ausgewählten Absatz gefundene Anmerkung abgelehnt wird.

async function rejectLast() {
  // Rejects the last annotation found in the selected paragraph.
  await Word.run(async (context) => {
    const paragraph: Word.Paragraph = context.document.getSelection().paragraphs.getFirst();
    const annotations: Word.AnnotationCollection = paragraph.getAnnotations();
    annotations.load("id,state,critiqueAnnotation");

    await context.sync();

    for (let i = annotations.items.length - 1; i >= 0; i--) {
      const annotation: Word.Annotation = annotations.items[i];

      if (annotation.state === Word.AnnotationState.created) {
        console.log(`Rejecting ID ${annotation.id}...`);
        annotation.critiqueAnnotation.reject();

        await context.sync();
        break;
      }
    }
  });
}

Anmerkungen löschen

Der folgende Code zeigt, wie alle Anmerkungen im ausgewählten Absatz gelöscht werden.

async function deleteAnnotations() {
  // Deletes all annotations found in the selected paragraph.
  await Word.run(async (context) => {
    const paragraph: Word.Paragraph = context.document.getSelection().paragraphs.getFirst();
    const annotations: Word.AnnotationCollection = paragraph.getAnnotations();
    annotations.load("id");

    await context.sync();

    const ids = [];
    for (let i = 0; i < annotations.items.length; i++) {
      const annotation: Word.Annotation = annotations.items[i];

      ids.push(annotation.id);
      annotation.delete();
    }

    await context.sync();

    console.log("Annotations deleted:", ids);
  });
}

Aufheben der Registrierung von Anmerkungsereignissen

Der folgende Code zeigt, wie Die Registrierung von Ereignishandlern mithilfe der in der eventContexts Variablen nachverfolgten Ereigniskontexte aufgehoben wird.

async function deregisterEventHandlers() {
  // Deregisters event handlers.
  await Word.run(async (context) => {
    for (let i = 0; i < eventContexts.length; i++) {
      await Word.run(eventContexts[i].context, async (context) => {
        eventContexts[i].remove();
      });
    }

    await context.sync();

    eventContexts = [];
    console.log("Removed event handlers.");
  });
}

Siehe auch