Can you provide guidance on utilizing OneNote JavaScript APIs to interpret indented paragraphs within OneNote?

I keep a notebook that contains the following entries:
https://i.stack.imgur.com/MLdO0.png

For information on OneNote APIs, you can refer to this link (paragraph class selected already) https://learn.microsoft.com/en-us/javascript/api/onenote/onenote.paragraph?view=onenote-js-1.1

When executing the following code:

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;
      
      //firstPageContent.delete()
      //var out_line=firstPageContent.outline
      paragraphs.load('richText/text');

      // Run the queued commands, and return a promise to indicate task completion.
      return context.sync()
        .then(function () {
              console.log("Items",paragraphs.items);
              for (var i = 0; i < paragraphs.items.length; i++) {
                  var paragraph = paragraphs.items[i];
                  paragraph.load('items');
                  context.sync();   
                  console.log(paragraph.richText.text);
                  show_next_level(paragraph, i);
              }

          });
    });
} catch (error) {
    console.log("Error: " + error);
}
}

export async function show_next_level(paragraph, i) {
  try {
    await OneNote.run(async context => {
      var paragraphs = paragraph.paragraphs;
      paragraphs.load('richText/text');

      // Run the queued commands, and return a promise to indicate task completion.
      return context.sync()
        .then(function () {

          console.log("Items", paragraphs.items);
          for (var i = 0; i < paragraphs.items.length; i++) {
              var subParagraph = paragraphs.items[i];
              subParagraph.load();

              context.sync();   
              console.log(subParagraph.richText.text);
              debugger;
              show_next_level(subParagraph, i);
          }
        });

    });
  } catch (error) {
    console.log("Error: " + error);
  }
}

After several iterations, I successfully managed to read the next level of indentation but encountered an error in the process. The current output is as follows:

Items (4) [h, h, h, h]
One line 1 
One line 2
One line 3
One line 4
Items [h]
Two line 0
Items (3) [h, h, h]
Two line 1
Two line 2
Two line 3
Items []
5taskpane.js:192 Error: PropertyNotLoaded: The property 'items' 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.

Answer №1

Your code has a problem where you are not properly handling Item Promises, resulting in a PropertyNotLoaded Error. This occurs because you are not waiting for the context sync, as shown in this line:

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

The corrected code below addresses multiple indented lines and utilizes await/async methods to handle 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();

      // For each 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 utilized this data for testing purposes, and you can view the results here.

This revised code should help resolve your issue!

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

JavaScript is a powerful tool for reading JSON files

I'm trying to figure out how to parse a nested object in JSON using JavaScript. Here's the code I have so far: var myRequest = new Request('test.json'); fetch(myRequest) .then(function(response) { return response.json(); }) .then( ...

Can the ES2016 Proxy be used to intercept the "typeof" operation?

Can a handler property be defined to intercept typeof proxyObject? It is not mentioned in any of the traps listed on Mozilla. ...

An unexpected problem with text redirection that should not be happening

I am facing an issue with my HTML text field and post button on my website. Whenever I click the post button to make a post, it redirects to a separate PHP file called post.php which handles PHP and MySQL code for posting. However, I want to avoid this red ...

Encountering an issue when transferring data between controllers utilizing a demo service

During my journey of learning AngularJS, I decided to create a small app that would allow data to be passed between two controllers using services. Below is the code snippet that showcases how I achieved this: The Controller Code <!DOCTYPE html> &l ...

Issue with Node Canvas/Resemble.js: The image provided has not finished loading during the load operation

Recently, I encountered a challenge while trying to utilize Resemble.js in a node environment. Despite some initial complications with installing canvas/cairo due to OS X Mavericks/XQuarts and Homebrew issues, I eventually succeeded. After making signific ...

Utilize Vue.js 3 and InertiaJs to Retrieve Session Information in Laravel 9

I am currently working on my initial Laravel project, incorporating Vuejs for the frontend. One of the key features of my application is allowing a Super admin to log in as a User (impersonate). By clicking on the Impersonate Button, the word impersonate g ...

Solving the checkbox toggle challenge with recursive functions | Recursive checkbox challenge

I'm currently working on creating a checkbox tree with the following data structure for items const checkboxes = [{ field: 'ARTICLE', id: 41, name: 'Article', parentId: null, checked: false, children: [ ...

ReactJS fetching previous data through POST request

I am facing an issue while trying to replicate Google Translate. I have an API that sends and returns data as expected during the first translation attempt. However, after changing the text and attempting another translation, it sends the updated text but ...

Dragging an image in KineticJS gets stuck after the drag operation is completed

My experience with KineticJS has been positive so far, but I have encountered an issue with dragging images. In the example below, I have set the image to be draggable, but after the initial drag, it seems like the image can't be moved again. var sta ...

Unable to connect to server using local IP address

Currently utilizing a freezer application () and encountering an issue where I can only access the server on localhost. I attempted to modify the settings.js file by replacing 127.0.0.1 with 0.0.0.0, rebuilt it, but it still persists on localhost. Even aft ...

Struggling with parameter passing issues and preparing code for seamless integration with MYSQL database

I've been dedicating the past four days to a project that I've crafted entirely by hand to test my JavaScript skills as I progress through Codecademy courses. The goal is to develop a browser-based checklist program, and so far, I've success ...

Steps for serving a "noop" document via HTTP

I am in the process of creating a CGI script that performs various functions. I am striving to maintain simplicity and portability within the script. My main objective is to provide users with a way to send a message to the server without losing the curren ...

Why might the Bootstrap menu be malfunctioning?

The reality is that Bootstrap is functional and widely used. Sharing the code could make a big difference in getting assistance! <ul class="top-header-contact-info secondary-menu"> <li class="nav-item dropdown-toggle"> ...

What steps do I need to take to include React in my background.js script for a chrome

I'm currently facing an issue with my React code that I need to include in my background.js file. However, I encountered the following error message: SyntaxError: Cannot use import statement outside a module The specific import causing this error is: ...

What could be causing the issue with my custom AlloyEditor UI extension?

After following the instructions in this guide to integrate alloyeditor as a WYSIWYG editor into Contentful, I successfully added the extension to my contentful staging space. However, despite copying the html page from the github repository and includin ...

Achieving a perfect circle can be accomplished by setting both the width and height to the same

Trying to make the height of an element equal to its width For example, aiming for a perfect circle Although the console displays equal values, the resulting height is noticeably greater than the width $('button').on('click', funct ...

Anticipate await and fulfill promises

I'm encountering issues when attempting to refactor nested Promise.all's into async/await. It seems like there might be a misunderstanding in how I should be utilizing Promise.all and await. The goal is to iterate through an array, perform an ac ...

Access the value of a variable passed from the view to the controller

Is there a way to retrieve a dynamically generated value from the view to the controller in AngularJS? <ng-option ng-repeat="w in details track by $index"> <div class="program-grid-row table-row" > <div> <a class= ...

What is the best way to use useCallback within loops?

I am currently exploring the concepts of memo and useCallback, and to better grasp them, I have created a simple example: import { memo, useCallback, useState } from "react"; import { Button, Text, TouchableOpacity, SafeAreaView } from "reac ...

Error encountered: Class not found exception in the context of JSONArray

import org.json.JSONArray; JSONArray json=new JSONArray(al); response.setContentType("application/json"); response.getWriter().print(json); } Despite having included the necessary jar in my project, I am encountering this error: SEVERE: Servle ...