How do I read OneNote indented paragraphs using OneNote Javascript APIs?

前端 未结 1 528
梦谈多话
梦谈多话 2021-01-21 17:57

I have a notebook that contains these

The docs for OneNote APIs are here (paragraph class selected already) https://docs.microsoft.com/en-us/javascript/api/onenote

1条回答
  •  [愿得一人]
    2021-01-21 18:48

    The problem in your code is that your are not waiting for Item Promises, so, It throws PropertyNotLoaded Error. It happens because you are not waiting for the context sync eg. in the line:

    context.sync() // It's a promise, so it requires .then() method
    console.log(paragraph.richText.text)
    debugger;
    

    The following code works for multiple indented lines and uses await/async methods to wait for promises:

    export async function run() {
      try {
        await OneNote.run(async (context) => {
          var page = context.application.getActivePage();
          var pageContents = page.contents;
          var firstPageContent = pageContents.getItemAt(0);
          var paragraphs = firstPageContent.outline.paragraphs;
    
          paragraphs.load('richText/text');
    
          // Run the queued commands, and return a promise to indicate task completion.
          await context.sync();
    
          // Foreach level 0 paragraph
          for (let paragraph of paragraphs.items) {
            // Read the paragraph
            await readParagraph(context, paragraph, 0);
          }
        });
      } catch (error) {
          console.log("Error: " + error);
      }
    }
    
    // Read Paragraph data and Child data
    async function readParagraph(context, paragraph, level) {
      try {
        paragraph.load('items');
    
        await context.sync();
        console.log('Level ' + level + ' > Data:', paragraph.richText.text);
    
        let levelParagraphs = paragraph.paragraphs;
        levelParagraphs.load('richText/text');
    
        await context.sync();
    
        for (let p of levelParagraphs.items) {
          await readParagraph(context, p, level + 1);
        }
      } catch (error) {
        console.log('Error in Level ' + level, error);
      }
    }
    

    I used these data for testing and these were the results.

    I hope it helps you!

    0 讨论(0)
提交回复
热议问题