The Office JS has provided the following function in preview, but I couldn't find any example.
Here is what I tried but it doesn't seem to work, any idea what I am missing here, since this code inserts the text but the bookmark is not created.
Word.run(function (context)
{
let range = context.document.getSelection();
return context.sync().then(function ()
{
range.insertText(`Test Bookmark`, Word.InsertLocation.replace);
let uniqueStr = new Date().getTime();
let bookmarkName = `Test_BookmarkCode_${uniqueStr}`;
range.insertBookmark(bookmarkName);
});
});
Cross posted here.
The bookmark name must start with a letter and cannot contain spaces. Use the underscore character to separate words. If you insert multiple bookmarks, enter a descriptive name that is easy to recognize. Select Add to place the bookmark.
On the Bookmark dialog box, select the bookmark name you want to move, or reuse, and click “Add”. The bookmark is moved to the newly selected text or new position in the document. The bookmark name has been reused in a different place in the document. Clicking “Add” to reuse or move a bookmark can be misleading.
So, here is the working code. Apparently, when we insertText, a new range is returned, we need to use that range to insertBookmark.
Word.run(function (context)
{
let range = context.document.getSelection();
return context.sync().then(function ()
{
let insertedTextRange = range.insertText(`Test Bookmark`, Word.InsertLocation.replace);
let uniqueStr = new Date().getTime();
let bookmarkName = `Test_BookmarkCode_${uniqueStr}`;
insertedTextRange.insertBookmark(bookmarkName);
});
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With