Search code examples
javascriptms-officeoffice-addinsword-addins

Control the selection range in Word document from Javascript Add-in


Given some range in the Word Document body text, I want to set the current selection to that range and replace the text within.

Does anyone know how I can control the current selection within a Word document from an add-in using the Javascript API? I can't seem to find anything in the documentation:

https://dev.office.com/reference/add-ins/word/word-add-ins-reference-overview

I understand I can get the current selection within a document using context.document.getSelection(), but how do I get any selection within a document or specify what part of the document is selected? How do I programmatically control what is selected in the document?


Solution

  • To get the selected range of user selection :

      // Run a batch operation against the Word object model.
            Word.run(function (context) {
    
                var range = context.document.getSelection(); // Create a range proxy object for the current selection.
                context.load(range);
                // Synchronize the document state by executing the queued commands,and return a promise to indicate task completion.
                return context.sync().then(function () {
    
                    if (range.isEmpty) //Check if the selection is empty
                    {
                        return;
                    }
                    var html = range.getHtml();
                    return context.sync().then(function () {
    
                        var htmlVal = html.value; //Get the selected text in HTML 
                   });
                 });
               });
    

    To set in the selected range of user:

        // Run a batch operation against the Word object model.
        Word.run(function (context) {
    
            var range = context.document.getSelection();// Create a range proxy object for the current selection.
    
           range.clear();                                                             
           range.delete();
    
          // Synchronize the document state by executing the queued commands, and return a promise to indicate task completion.
           return context.sync().then(function () {
    
             range.styleBuiltIn = "Normal";                                                               
             range.insertText("your text"); // Queue a command to insert the encrypted text instead the current text 
          });
       })
    

    So if you have somehow already the 'range' you don't need to get it.

    ** If you don't want to take user selection and want to change just some part on document you could achieve it with paragraph selection , you could find more information about paragraph object and what you could do with this here: https://dev.office.com/reference/add-ins/word/paragraph

    good luck