I am building a word add-in, one of the main functions is that it can insert comments in specific parts of the document. The whole thing works well when used in locally installed Word, but as soon as we shift things to online web-based Word, and try to add comments programmatically, the following things happen on the UI:
But, as soon as I refresh the whole page by clicking the refresh button on my browser, magically all the comments start showing up.
Here's my implementation:
async function addCommentsToDoc(targetString: string, commentText: string) {
// Calling run method from Word package, to initialize the context
const result = Word.run(async (context) => {
await context.sync();
// Handling Word's 255 character search limit
if (targetString.length >= 255) {
targetString = targetString.slice(0, 250);
}
// Cleaning the location
targetString = targetString.trim()
// Getting the complete content of the current open document or content
const body = context.document.body;
// Using the native .search() method to search within a string.
const searchResults = body.search(
targetString,
{
matchCase: false,
matchWholeWord: false,
ignoreSpace: true,
ignorePunct: false,
matchPrefix: false,
matchSuffix: false,
matchWildcards: false
}
);
// Loading the searched properties from the document
context.load(searchResults, "text");
await context.sync();
if (searchResults.items.length > 0) {
//Skip the comments who's length is 0
if (commentText.length == 0) {
return;
}
// Adding the comment to the target string
const comment: Word.Comment = searchResults.items[0].insertComment(commentText);
comment.track();
comment.load(
"id, content, authorName, contentRange, resolved, replies"
);
await context.sync();
const range = comment.getRange();
range.select("Start");
await context.sync();
return true;
} else {
return false;
}
});
}