How to add a bookmark to the current position dynamically and get range

My requirement is to add a text in the current cursor position and mark it as bookmark. After making it as bookmark highlight it to a color

Below is the code

        const oDocument = Api.GetDocument();
        var oParagraph = Api.CreateParagraph();
        oParagraph.AddText(`${Name}`);
        oDocument.InsertContent([oParagraph], true);
        var oRange = oParagraph.GetRange(0, oParagraph.GetText().length)
        oRange.AddBookmark('uniqueBookmarkId');
        oRange.SetHighlight('green');

The text gets inserted at the current cursor position. But, it fails to be added as bookmark .
oRange returns some of the fields as undefined like below

Could anyone please help me to fix the issue or provide any work arounds?

Hello @SaiVaishnavi

You can use handy workaround with Search and SearchAndReplace methods for such task:

var oDocument = Api.GetDocument();
var oParagraph = Api.CreateParagraph();
var oTempObj = "Some ID";  // Unique string that won't correspond to any text in the document and which must exceed length of replacement string, i.e. oName in this example
var oName = "Name";  // Your name variable 
oParagraph.AddText(oTempObj); // Adds temporary string into the documents for further replacement 
oDocument.InsertContent([oParagraph], true);
var aSearch = oDocument.Search(oTempObj, true); //  Performs search for temp object and returns range
oDocument.SearchAndReplace({"searchString": oTempObj, "replaceString": oName}); // Replaces temp object with your variable and modifies the range
aSearch[0].AddBookmark('uniqueBookmarkId'); // Adds bookmark to modified range
aSearch[0].SetHighlight('green'); // Sets color to the modified range

Example above will replace temp object string with a name from oName variable, add this range as a bookmark and also highlight it.

However, this method has a caveat:

Length of oTempObj (temp object for replacement) must always exceed the length of possible oName variable, otherwise part of the name won’t be highlighted and certain part of the name won’t be added as bookmark.

I hope it suits your goal.

1 Like