8

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.

6
  • As this is beta preview API, are you referring to the beta CDN?appsforoffice.microsoft.com/lib/beta/hosted/office.js Commented Jun 12, 2020 at 6:32
  • @RaymondLu Yes, I am. <script src="appsforoffice.microsoft.com/lib/beta/hosted/office.js" type="text/javascript"></script> Commented Jun 12, 2020 at 8:08
  • 1
    I have tried your code, if i remove this line, it will work, can you have a try? range.insertText(Test Bookmark`, Word.InsertLocation.replace); Commented Jun 12, 2020 at 8:43
  • @RaymondLu Yes, it worked. Is there a way to add new text and set it as bookmark? Commented Jun 12, 2020 at 9:55
  • @RaymondLu I've posted an answer, all I had to do is to use the range returned by range.insertText to insertBookmark. Commented Jun 12, 2020 at 10:22

2 Answers 2

3

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);
    });
});
Sign up to request clarification or add additional context in comments.

Comments

0

(Cannot comment, pls excuse my posting this as an answer.) Two things that got in my way when I implemented something similar to the above solution:

  1. The bookmark name may not be longer than 40 characters.
  2. The name may contain underscores (_), but no dashes (-). Probably most other punctuation characters aren't permitted either.

If you violate either rule you'll get an InvalidArgument exception. I only tried this with the Windows Desktop version of Word 2019, but this behavior is probably the same with other versions.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.