Word 加载项 - 如何阅读自定义文档 属性

Word Add-in - How to read custom document property

我正在使用 Office JS 开发一个 Word 插件 API。

目前我可以通过以下方式向 Word 文档添加自定义属性:

context.document.properties.load();
context.document.properties.customProperties.add("file-name-prop", "my file name");

如果我随后下载文件,我可以在压缩的 docx 中的 "custom.xml" 文件中看到 属性。

但是我无法读回 属性。

我正在尝试这样做:

context.document.properties.load();
var filenameProp = context.document.properties.customProperties.getItemOrNullObject("file-name-prop");
if (filenameProp) {
    // use filenameProp.value
} else {
    // ignore, property not set
}

这样做时,出现以下错误:

code : "PropertyNotLoaded"
message : "The property 'type' is not available. Before reading the property's value, call the load method on the containing object and call "context.sync()" on the associated request context."
name : "OfficeExtension.Error"

阅读 属性 的正确方法是什么?

(我用的是这个office js:appsforoffice.microsoft.com/lib/beta/hosted/office.js)

可能是您没有包含您的代码部分,但我没有看到您同步上下文的任何地方。您提供的错误消息表明相同的内容:“在读取 属性 的值之前,对包含的对象调用加载方法并在关联的对象上调用“context.sync()”请求上下文。”。看起来您完全或部分缺少 context.sync()。同步上下文后,您应该能够获取自定义属性。例如,要创建自定义 属性,代码应类似于 ...

function setProperty (prop_name, prop_value) {
  Word.run(function (context) {
    context.document.properties.customProperties.add(prop_name, prop_value);
    return context.sync()
      .catch(function (e) {
        console.log(e.message);
      })
  })
}

并且当您需要获得 属性 时,代码仍然使用“同步”来使 属性 可用。例如,要获得自定义 属性,代码应类似于 ...

function getProperties() { 
    Word.run(function (context) {
        var customDocProps = context.document.properties.customProperties;
        context.load(customDocProps);
        return context.sync()
            .then(function () {
                console.log(customDocProps.items.length);
             })
     })
}

Slava 的回答是正确的,但要真正读取 属性 值,我还必须实际加载那个值,我觉得这很复杂,但是...

最终工作代码(借用 Slava 的示例):

function getPropertyValue() { 
  Word.run(function (context) {
    var customDocProps = context.document.properties.customProperties;
    // first, load custom properties object
    context.load(customDocProps);
    return context.sync()
      .then(function () {
        console.log(customDocProps.items.length);
        // now load actual property
        var filenameProp = customDocProps.getItemOrNullObject("file-name-prop");
        context.load(filenameProp);
        return context.sync()
          .then(function () {
            console.log(filenameProp.value);
          });
      });
  });
}