# OpenAndSave

The following example demonstrates how to open a browser instance, save and restore a session, visit a webpage, perform actions (like login), and close the browser. The session is saved so that the next time the browser is opened, it restores the previous session without requiring you to log in again.

```javascript
const svc = new BrowserService(token);

// FIRST VISIT --------------------------------------------------------------------
let browser = await openAndConnect(svc);
if (!browser) return;

let page = (await browser.pages())[0];

await page.goto("http://app.cloudbrowser.ai");
console.log("Web visited");

await login(page);
await new Promise((resolve) => setTimeout(resolve, 5000));

await browser.close();
console.log("Browser closed");

// SECOND VISIT -------------------------------------------------------------------
await new Promise((resolve) => setTimeout(resolve, 1000));

browser = await openAndConnect(svc);
if (!browser) return;

page = (await browser.pages())[0];

await page.goto("http://app.cloudbrowser.ai");
console.log("Web visited again");

// This time, logging in is not necessary.
await new Promise((resolve) => setTimeout(resolve, 5000));

await browser.close();
console.log("Browser closed");

// CHECK STORED SESSIONS ----------------------------------------------------------
const sessions = new SessionService(token);
console.log("Label | Created On | Last Update");
const sessionRp = await sessions.list();
for (const s of sessionRp.sessions ?? []) {
    console.log(`${s.label} | ${s.createdOn} | ${s.lastUpdate}`);
}

// REMOVE ONE SESSION
await sessions.remove("test");
}

async function openAndConnect(svc: BrowserService) {
const rp = await svc.open({
    label: "SessionSample",
    saveSession: true,
    recoverSession: true,
});

if (rp.status !== ResponseStatus.SUCCESS || rp.address == null) {
    console.log(`Error requesting browser: ${rp.status}`);
    return null;
}
console.log("Browser requested");

return await puppeteer.connect({
    browserWSEndpoint: rp.address,
    defaultViewport: null,
    slowMo: 0,
});
}
```

***

#### F**ull example**

{% embed url="<https://github.com/CloudBrowser-AI/CloudBrowserAiNodeJS/blob/main/samples/save-restore-session/src/index.ts>" %}

This code demonstrates the use of a browser service to manage session-based automation tasks with Puppeteer. It consists of three main parts:

#### **1. First Visit**

* A browser instance is created and connected using the `openAndConnect` function, which initializes a session with options to save and recover it later.
* A new page is opened, and the script navigates to `http://app.cloudbrowser.ai`. After the page loads, a `login` function is invoked to authenticate, followed by a 5-second delay.
* The browser is then closed, logging its closure.

#### **2. Second Visit**

* After a short delay (1 second), the browser session is reopened using `openAndConnect`.
* The same page (`http://app.cloudbrowser.ai`) is revisited, but logging in is skipped since the session recovery is enabled.
* A delay of 5 seconds is added before closing the browser again, and the closure is logged.

#### **3. Session Management**

* A `SessionService` instance is created to manage stored browser sessions.
* The script lists all active sessions, logging details like their labels, creation dates, and last update times.
* Finally, a session with the label `"test"` is explicitly removed.

#### **Key Functionality**

The `openAndConnect` function handles:

* Requesting a browser instance with session management options (`saveSession` and `recoverSession`).
* Handling connection errors, returning `null` if the browser cannot be opened.
* Establishing a Puppeteer connection using the provided WebSocket endpoint.

This setup enables efficient session handling and reusability, avoiding redundant login steps and providing visibility into session usage.


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://cloudbrowser.gitbook.io/docs/libraries/node.js-client/openandsave.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
