Microsoft Word JavaScript API - event handler for text selection in document
Asked Answered
D

1

6

I read JavaScript API for Office and I couldn't find a handler to notify when user select a text in the word document.

I am aware that we can copy the selected/highlighted text from document as follow:

Word.run(function(context) {
    let body = context.document.body;

    // ask for the user selected text
    let range = context.document.getSelection();
});

This approach is not a registered callback or an event. With this approach I have to request update or to check if user selected anything.

Is there an existing function that I can register for getting notified for user interaction with document?

Thanks in-advance for your help

Dispense answered 4/9, 2018 at 0:0 Comment(1)
Have you seen this in the documentation learn.microsoft.com/en-us/office/dev/add-ins/develop/… in the section "Detect changes in the selection". You'll also find code in #44060520Bluecollar
G
8

the getSelection() method does not actually make a selection in the document. it gives you the range that its currently selected. in order to get the events you need to subscribe to the document selection event, you can achieve that fairly simple just with:

function subscribeToEvent() {
    Office.context.document.addHandlerAsync(Office.EventType.DocumentSelectionChanged, handler);
}

function handler(evtArgs) { 
  // here you can handle the event. 
    console.log("select");
}

On the other hand the range.select() method WILL trigger the selection changed event if you want todo it programmatically. Please check out this Script Lab snippet, it basically subscribe to the event on load, then if you click the RUN button you will see that the last paragraph gets selected and the event triggered.

Genetic answered 5/9, 2018 at 17:53 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.