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

Deadly 提交于 2020-12-06 05:35:09

问题


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


回答1:


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.



来源:https://stackoverflow.com/questions/52157240/microsoft-word-javascript-api-event-handler-for-text-selection-in-document

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!