> For clean Markdown of any page, append .md to the page URL.
> For a complete documentation index, see https://docs.airtop.ai/llms.txt.
> For AI client integration (Claude Code, Cursor, etc.), connect to the MCP server at https://docs.airtop.ai/_mcp/server.

## Overview

This recipe demonstrates how to use Airtop to automate human interactions with a browser and extract stock performance data. It also makes use of Airtop's page query API to fetch and process data from the web page.

The instructions below will guide you through creating a script that:

* Connects to Airtop
* Initializes a browser session and window
* Navigates to a stock performance page using click and type interactions
* Extracts data using the page query API
* Displays the data in a formatted manner

## Demo

A live demo of this recipe is available [here](https://examples.airtop.ai/simple-interactions). You can [sign up](https://portal.airtop.ai/) to create an API key for free and try it out yourself!

## Prerequisites

To get started, ensure you have:

* Node.js installed on your system.
* PNPM package manager installed. See [here](https://pnpm.io/installation) for installation steps.
* A Node Version Manager (NVM preferably).
* An Airtop API key. You can [get one for free](https://portal.airtop.ai/api-keys).

## Getting Started

1. **Clone the repository**

   Start by cloning the source code from [GitHub](https://github.com/airtop-ai/examples-typescript):

   ```bash
   git clone https://github.com/airtop-ai/examples-typescript
   cd examples-typescript/examples/simple-interactions
   ```

2. **Setup**

   Follow the README instructions in the root of the cloned repository to install dependencies and build packages. Then follow the instructions in `examples/simple-interactions/README.md`.

## Script Walkthrough

The script in `simple-interactions.cli.ts` performs the following tasks:

1. **Initialize the Logger and Prompt for API Key**

   The script starts by initializing a logger and prompting the user for their Airtop API key.

   ```typescript
   const log = getLogger();

   const apiKey = await input({
     message: "Enter your Airtop API key:",
     required: true,
   });
   ```

2. **Create an InteractionsService Instance**

   An instance of `InteractionsService` is created using the provided API key, logger and a default ticker symbol. This service handles interactions with the browser.

   ```typescript
   const service = new InteractionsService({
     apiKey,
     log,
     ticker: DEFAULT_STOCK_SYMBOL,
   });
   ```

3. **Initialize Session and Browser**

   The script initializes a session and browser window using the `initializeSessionAndBrowser` method from `InteractionsService`.

   ```typescript
   sessionAndWindow = await service.initializeSessionAndBrowser();
   const { session, windowInfo } = sessionAndWindow;
   ```

   **Under the Hood:**

   ```typescript
   async initializeSessionAndBrowser() {
     // Create a new session
     const createSessionResponse = await this.client.sessions.create({
       configuration: {
         timeoutMinutes: 10, // Terminate the session after 10 mins of inactivity
       },
     });

     const session = createSessionResponse.data;
    
     // Open a new browser window with the default URL
     const windowResponse = await this.client.windows.create(session.id, {
       url: INITIAL_URL,
     });

     // Get the window information
     const windowInfo = await this.client.windows.getWindowInfo(session.id, windowResponse.data.windowId);

     // Return session and window information, including a live view
     return { session, windowInfo };
   }
   ```

4. **Search for Stock Performance**

   The script uses the `searchForStockPerformance` method to search for stock performance data.

   ```typescript
   await service.searchForStockPerformance({
     sessionId: session.id,
     windowId: windowInfo.data.windowId,
   });
   ```

   **Under the Hood:**

   ```typescript
   async searchForStockPerformance({ sessionId, windowId }: { sessionId: string; windowId: string }) {
    // Type the ticker symbol into the search box and press enter
    await this.client.windows.type(sessionId, windowId, {
      elementDescription: "The search box",
      text: this.ticker,
      pressEnterKey: true,
    });
   }
   ```

5. **Click on Stock Performance Chart**

   The script simulates a click on the stock performance chart using the `clickOnStockPerformanceChart` method.

   ```typescript
   await service.clickOnStockPerformanceChart({
     sessionId: session.id,
     windowId: windowInfo.data.windowId,
   });
   ```

   **Under the Hood:**

   ```typescript
   async clickOnStockPerformanceChart({ sessionId, windowId }: { sessionId: string; windowId: string }) {
     // Identify the chart element using natural language and simulate a click
     await this.client.windows.click(sessionId, windowId, {
       elementDescription: "The '6M' button at the top of the chart",
     });
   }
   ```

6. **Extract Stock Performance Data**

   The script extracts stock performance data using the `extractStockPerformanceData` method and formats it for display.

   ```typescript
   const content = await service.extractStockPerformanceData({
     sessionId: session.id,
     windowId: windowInfo.data.windowId,
   });

   const formattedJson = JSON.stringify(JSON.parse(content), null, 2);
   log.info("Response:\n\n", chalk.green(formattedJson));
   ```

   **Under the Hood:**

   ```typescript
   async extractStockPerformanceData({ sessionId, windowId }: { sessionId: string; windowId: string }) {
     // Use the pageQuery API to extract stock performance data
     const modelResponse = await this.client.windows.pageQuery(sessionId, windowId, {
       prompt: STOCK_PERFORMANCE_PROMPT(this.ticker),
       configuration: {
         outputSchema: STOCK_PERFORMANCE_OUTPUT_SCHEMA(this.ticker),
       },
     });

     // Return the extracted data
     return modelResponse.data.modelResponse;
   }
   ```

7. **Clean Up**

   Finally, the script ensures that the session is terminated to clean up resources.

   ```typescript
   if (sessionAndWindow?.session) {
     await service.terminateSession(sessionAndWindow.session.id);
   }
   ```

   **Under the Hood:**

   ```typescript
   async terminateSession(sessionId: string) {
     // Terminate the session to release resources
     await this.client.sessions.terminate(sessionId);
   }
   ```

## Running the Script

To run the script, execute the following command in your terminal:

```bash
pnpm run cli
```

This command uses the `cli` script defined in the `package.json` file, which runs the `simple-interactions.cli.ts` file using `tsx`.

## Summary

This recipe demonstrates how Airtop can be utilized to automate tasks that require browser interactions which would otherwise require manual intervention. Compounded with other Airtop APIs like the [page query API](/api-reference/airtop-api/windows/page-query), it can be used to build powerful automation workflows.