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

Changing a button's text in Vue.js when holding a keyboard modifier - how to do it!

While working with Vue, I am attempting to modify a button's behavior when the Shift key is pressed. Adjusting the behavior of the click event was straightforward: @click.exact="goForward" @click.shift="goBackward" However, I am f ...

What is preventing the table from extending to the full 100% width?

Displayed above is an image showing an accordion on the left side and content within a table on the right side. I have a concern regarding the width of the content part (right side) as to why the table is not occupying 100% width while the heading at the ...

Creating smooth and natural movement of a div element using Javascript (rotating and moving)

After struggling to use jquery plugins for smooth motion with the div elements I'm working on, I've decided it's time to seek some assistance. I have a group of div elements that all share a class and I want them to move around the screen c ...

Utilize a Java application to log in to a website automatically without the need to click on

Opening two websites in my application is a requirement. Both of these websites have login forms with the action set to POST method. My goal is to automatically redirect to the next page after logging into these websites when I access them through my proj ...

Processing a JSON array of objects in AngularJS

When using Angular's fromJson function to parse a JSON string, I encountered an issue. If the JSON is a simple array like "[1, 2]", the code works fine. However, I need to work with an array of dictionaries instead. var str = "[{'title' ...

Expressjs Error- ReferenceError: cors has not been defined in this context

While working on creating a backend using ExpressJs, I encountered an error when running the backend. app.use(cors()) ^ ReferenceError: cors is not defined at Object.<anonymous> (C:\Users\hp\Desktop\Entri\kanba\ ...

Issue encountered when sending information to asmx web service via ajax and displaying the result on an HTML page with a javascript function

I have developed an ASMX web service that looks like this: [ScriptService] public class CurrencyData : System.Web.Services.WebService { [WebMethod] public string DisplayCurrency(double amount, string sign ,string style) { swi ...

You are unable to move the image to the top of the screen after zooming it with CSS

I implemented an image viewer component with interactive buttons for rotating, zooming in, and zooming out. Upon clicking a button, CSS transform is applied to the image. However, I encountered an issue where, when zooming the image, it cannot be scrolled ...

What could be the reason for the child element not occupying the full height of its parent container?

* { padding: 0; margin: 0; box-sizing: border-box; } body { margin: 50px; } .navbar { display: flex; align-items: center; justify-content: center; color: darkgreen; font-family: 'Vollkorn', serif; font-size: 1.2rem; font-w ...

Retrieving the value of an ASP.NET Literal in JavaScript

Is there a way to retrieve the value of an ASP.NET Literal control in JavaScript? I attempted the code below but it didn't return any values: var companyName = document.getElementById('litCompanyName').textContent; var companyNumber = docum ...

Stop users from signing up if the chosen username is already in use

I have a script that successfully checks if a username is available, but even if the username is already taken, the user can still register. I am looking for a way to prevent registration if the username is not free. Here is the code snippet: index.php $ ...

Tips for integrating Tornado authentication with AngularJS

I have been experimenting with the authentication system outlined in the tornado documentation, and I am encountering a Cross-Origin Request issue when trying to integrate it with AngularJS. Is there a way to successfully combine Tornado's authentica ...

Affixing a navigation bar to the top while scrolling

Does anyone know how to create a navigation bar that will "dock" to the top of the browser when scrolled to, and undock when scrolled back up? Check out my code snippet here: http://jsfiddle.net/gLQtx/ $(function() { var initPos = $('#stickyNav&apo ...

Updating Values in Nested Forms with Angular Reactive Form

I have been grappling with a form setup that looks something like this: itemEntities: [ {customisable: [{food: {..}, quantity: 1}, {food: {..}, quantity: 5}]}, {customisable: [{food: {..}, quantity: 0}]}, ] My challenge lies in trying to u ...

Error alert: TypeScript typings issue - Naming conflict with Promise / Failure to locate name Promise

I am currently working on a client/server JavaScript application and I am facing a significant issue with Promises. It appears that they are either undefined or duplicated, and this problem seems to be related to the @types package. npm install --save @ty ...

`How can I retrieve a PHP variable using a JavaScript AJAX request?`

When sending an AJAX request, I encounter a situation where: //javascript var rq = new XMLHTTPrequest(); rq.open('POST','test.php', true); rq.send(JSONString); Within "test.php" file, the following action is taken: //php $data = "Hel ...

How to use Javascript to toggle a popup containing an autoplaying Vimeo video

I am looking to create a pop-up window containing a Vimeo video inside. I have a div on my webpage with an id of "showVideo". When this div is clicked, I want to display a pop-up (new div with the id of "opened-video"). The "opened-video" div contains an i ...

Update the value of a td element when a select option is changed in another td element within the same table row

I have a table set up as follows: Header1 | Header2 | Header3 | Header 4 | Header 5 Row 1 |<span>Some Text</span> | <select></select> Row 2 Row 3 . . . . Rows generated dynamically. My objecti ...

The thickness of the line on the Google line chart is starting to decrease

Currently, I am utilizing a Google line chart in my application. However, I have noticed that for the first two data points, the lineWidth is thick, while for the last two points it is very thin. How can I resolve this issue and ensure that the lineWidth r ...

Looking to design an interactive grid for generating dynamic thumbnails

I am a beginner in the field of web development and I have a desire to create a website for showcasing my portfolio. This website should feature project thumbnails along with brief descriptions, all of which should be displayed dynamically. Although I poss ...