Search code examples
ms-wordoffice365ms-officeoffice-jsoffice365-apps

Office JavaScript API: selecting a range in Word for Mac


I'm working on a side project using the Microsoft Office JavaScript APIs. I have some functionality working to select a range in order to scroll to a particular position within a document. This works as expected in Office for the web, but in Office for Mac I get the following error when calling context.sync().then():

Unhandled Promise Rejection: RichApi.Error: ItemNotFound

I can't find any documentation on that particular error, and I'm not sure how to troubleshoot what I might be doing wrong. What am I missing? Like I said, this works in the web interface.

Here is minimal sample of code that demonstrates the problem:

function UI(context) {
    this.context = context;
}

UI.prototype.initialize = function() {
    var paragraphs = this.context.document.body.paragraphs;
    this.context.load(paragraphs);

    document.querySelector('button').addEventListener('click', () => {
        this.context.sync().then(() => {
            this.goToRange(paragraphs.items[0]);
        });
    });
};

UI.prototype.goToRange = function(range) {
    range.select();
    this.context.sync();
};

document.addEventListener('DOMContentLoaded', () => {
    Office.onReady(() => {
        Word.run(context => {
            return context.sync().then(() => {
                new UI(context).initialize();
            });
        });
    });
});

The only thing I can think of is that maybe the reference to the paragraph client object becomes "stale" in some sense, perhaps based on some resource limits that are lower in the Mac application than in the online interface? (That would be counterintuitive to me, but it's the only thing that comes to mind.)


Solution

  • I think I figured out the problem. I stumbled upon a hint while putting together the minimum code sample in the question; I removed a little too much code at first and encountered the following error:

    Unhandled Promise Rejection: RichApi.Error: The batch function passed to the ".run" method didn't return a promise. The function must return a promise, so that any automatically-tracked objects can be released at the completion of the batch operation.

    I believe the issue is that, at least in Word for Mac, you can't use the context object provided by Word.run in an asynchronous event listener. I'm guessing this is because, as the above error states, some state has been released after resolving the promise returned. I can get the code to work by adding a dedicated call to Word.run (and using the fresh context provided) inside the event listener.

    It is still a little odd that it works just fine in the browser. Presumably, the same state is not released as aggressively in the browser-based version.