Dan Tao
Dan Tao

Reputation: 128317

Office JavaScript API: highlighting text in a document

I'm working on a side project using the Microsoft Office JavaScript APIs. I have been relying on the documentation to find my way around, but I've hit a wall trying to find something in the docs (perhaps it isn't there because it doesn't exist).

Recently I attempting to implement some functionality to highlight some text within a Word document. I don't want to modify the document, mind you; in other words I would rather not use something like ContentControl.insertHtml as that would change the actual content. What I want is to make the text temporarily highlighted (e.g., until the user clicks a "Cancel" button), much like what you see when you perform a search with Ctrl+F (and text matching your search is highlighted in yellow).

Is this possible using the Office JavaScript APIs?

Upvotes: 2

Views: 2027

Answers (3)

Chris O'Sullivan
Chris O'Sullivan

Reputation: 1272

There's now a highlight method in office.js that might solve your issue. From the docs:

Highlights the range temporarily without changing document content. To highlight the text permanently, set the range's Font.HighlightColor.

You can call it from any range with:

range.highlight()

One great thing about it is that it's temporary, so if you close your add-in it disappears.

Find out more here: https://learn.microsoft.com/en-us/javascript/api/word/word.range?view=word-js-preview#word-word-range-highlight-member(1)

Upvotes: 0

RBILLC
RBILLC

Reputation: 190

Here is a sample application that uses font.highlightcolor from the Office Javascript API. https://github.com/OfficeDev/Word-Add-in-JS-Redact/

Upvotes: 0

Rick Kirkham
Rick Kirkham

Reputation: 9659

Try getting a reference to the Range object and then setting Range.font.highlightcolor. Have a handler for the Cancel button click event that reverses the color change.

Upvotes: 2

Related Questions