Search code examples
javascriptoffice-jsadd-inoffice-addinscpu-word

Unable to read Content Controls in existing Word document using office.js APIs


I am trying to get a handle on list of existing Content Control within a Word document with the office.js add-in framework but am unable to do so. I have even tried adding my own Content Control and then requested for Content Control, but the API fails to respond. Below is my code snippet.

Appreciate if you can advise how I can get a list of all Content Controls within the Word Document. FYI, using getByTag() didn't work either.

Office.onReady((info) => {
  document.getElementById("host-info").innerText = info.host.toString();
  document.getElementById("sideload-msg").style.display = "none";
  document.getElementById("app-body").style.display = "flex";
  document.getElementById("run").onclick = run;
  document.getElementById("count-controls").onclick = countControls;
});

export async function run() {
  return Word.run(async (context) => {
    /**
     * Insert your Word code here
     */

    const text = context.document.body.insertText("FIlling some random text ", Word.InsertLocation.start);
    text.font.underline = Word.UnderlineType.dotDashLineHeavy;

    const controls = text.insertContentControl();
    controls.title = "My text";
    controls.tag = "#mytext";
    controls.appearance = "Tags";
    controls.color = "red";

    await context.sync();
  });
}

export async function countControls() {
  console.log("In Count Controls");
  return Word.run(async (context) => {
    let numberOfControls = context.document.contentControls.items.length;  // <-- This line fails to respond with any content
    const para = context.document.body.insertParagraph(
      "Number of controls: " + numberOfControls,
      Word.InsertLocation.end
    );
    para.font.color = "blue";
    await context.sync();
  }).catch((error) => {
    console.log("Error: " + JSON.stringify(error));
    if (error instanceof OfficeExtension.Error) {
      console.log("Debug info: " + JSON.stringify(error.debugInfo));
    }
  });
}


Solution

  • You need to load items before reading its length:

    let contentControls = context.document.contentControls;
    contentControls.load('items');
    await context.sync();
    let numberOfControls = contentControls.items.length;