从 Javascript 加载项控制 Word 文档中的选择范围

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

给定 Word 文档正文中的某个范围,我想将当前选择设置为该范围并替换其中的文本。

有谁知道如何使用 Javascript API 从加载项控制 Word 文档中的当前选择?我似乎在文档中找不到任何内容:

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

我知道我可以使用 context.document.getSelection() 获取文档中的当前选择,但是我如何获取文档中的任何选择或指定文档的哪个部分被选中?如何以编程方式控制在文档中选择的内容?

获取用户选择的选择范围:

  // 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 
               });
             });
           });

用户的选定范围内设置:

    // 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 
      });
   })

因此,如果您已经以某种方式获得 'range',则无需获取它。

** 如果您不想进行用户选择而只想更改文档的某些部分,您可以通过段落选择来实现,您可以在此处找到有关段落对象以及您可以使用它做什么的更多信息: https://dev.office.com/reference/add-ins/word/paragraph

祝你好运