1

In a Word add-in, I'm trying to:

  1. receive documentSelectionChanged events,
  2. get the text of the current paragraph, and
  3. replace the string foo with the string bar in the current paragraph.

Everything is working except the last part. The text of the Word document isn't changing.

This is my code:

function updateText() {
  var range, foo_range, par;
  Word.run(function (context) {
    range = context.document.getSelection();
    range.paragraphs.load('items');
    return context.sync()
    .then(function() {
      par = range.paragraphs.items[0];
      console.log(par.text); // THIS WORKS!
      foo_range = par.search('foo');
      foo_range.load('items');
    })
    .then(context.sync)
    .then(function() {
      console.log(foo_range.items[0].text); // THIS WORKS!
      foo_range.items[0].insertText('bar', 'Replace');
      // Here, I am trying all the load options I can think of 
      foo_range.load('items');
      foo_range.items[0].load('text');
      foo_range.load('text');
      range.paragraphs.load('items');
      range.paragraphs.load('text');
      return context.sync();
    });
  });
}

Any idea why foo doesn't get replaced by bar in the Word document?

new name
  • 15,861
  • 19
  • 68
  • 114

1 Answers1

1

I can't reproduce. Your code works for me on desktop Office 365.

BTW, none of those load calls before the last context.sync do anything, and you should delete them. You only need to load a property (and then sync) when you are going to read the property after the sync. Since you are only writing to the document, you don't need to load anything.

Rick Kirkham
  • 9,038
  • 1
  • 14
  • 32
  • Strange, this is the second time that my code works for you but not for me. Any idea of where the problem might be? E.g., Mac-specific bug, configuration in manifest, or something else? – new name Apr 02 '20 at 17:24
  • First, see if your code works in [the Script Lab tool](https://appsource.microsoft.com/en-us/product/office/WA104380862?src=office&corrid=dff7bec8-77da-4fa7-90a0-a44bb6203209&omexanonuid=05903015-be38-40af-b6c5-af5743f98476&referralurl=https%3a%2f%2fwww.microsoft.com%2fen-us%2fgarage%2fprofiles%2fscript-lab%2f). If not, I would suspect a Mac-specific bug, in which case you should raise an issue on the [office-js repo](https://github.com/OfficeDev/office-js/issues). – Rick Kirkham Apr 02 '20 at 17:41
  • 1
    Rick, so the problem turned out to be the permissions in my manifest. I had `ReadAllDocument` but I need `ReadWriteDocument `. I had forgotten that the manifest had such permissions. – new name Apr 19 '20 at 00:15