Office JavaScript API:在 Word 中为 Mac 选择范围

Office JavaScript API: selecting a range in Word for Mac

我正在使用 Microsoft Office JavaScript API 进行一个副项目。我有一些功能可以 select 一个范围,以便滚动到文档中的特定位置。这在 Office for web 中按预期工作,但在 Office for Mac 中调用 context.sync().then():

时出现以下错误

未处理的承诺拒绝:RichApi.Error:ItemNotFound

我找不到关于该特定错误的任何文档,而且我不确定如何解决我可能做错的问题。我错过了什么?就像我说的,这在网络界面中有效。

这是演示问题的最小代码示例:

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

我唯一能想到的是,在某种意义上,对段落客户端对象的引用可能会变成 "stale",也许是基于 Mac 应用程序中低于某些资源限制的应用程序在在线界面? (这对我来说是违反直觉的,但这是我唯一想到的。)

我想我找到了问题所在。在将问题中的最小代码示例放在一起时,我偶然发现了一个提示;我一开始删除了太多代码,遇到了以下错误:

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.

我认为问题在于,至少在 Mac 的 Word 中,您不能在异步事件侦听器中使用 Word.run 提供的 context 对象。我猜这是因为,正如上面的错误状态,在解决返回的承诺后,一些状态已经被释放。我可以通过在事件侦听器中添加对 Word.run 的专用调用(并使用提供的新 context)来使代码工作。

它在浏览器中工作得很好,这仍然有点奇怪。据推测,相同的状态在 browser-based 版本中没有被积极释放。