Search code examples
ms-officeoffice365office-jsoffice-addins

Word Add-in - How to read custom document property


I am developing a Word plugin using the Office JS API.

Currently I can add custom properties to the Word document by doing:

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

If I then download the file I can see the property in the "custom.xml" file inside the zipped docx.

But I am not able to read the property back.

I am trying to do it like this:

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

When doing that, I am getting the following error:

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"

Which would be the right way to read the property back?

(I am using this office js: appsforoffice.microsoft.com/lib/beta/hosted/office.js)


Solution

  • May be you didn't include the parts of your code, but I don't see anywhere you sync context. The error message you have provided indicates the same: "Before reading the property's value, call the load method on the containing object and call "context.sync()" on the associated request context.". Looks like you are missing context.sync() at all or partially. You should be able to get custom properties after the context is synced. For example to create custom property the code should look similar to ...

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

    And when you need to get a property the code is still uses "sync" to make property available. For example to get custom property the code should look similar to ...

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