# Browser API

Import `browser` from `azot` to open a page for interactive login or run JavaScript in a website's context.

```ts
import { browser } from "azot";
```

Browser pages are available only in the Azot desktop app, including hidden pages. In the standalone CLI, `browser.newPage()` rejects with `Interactive browser pages are available only in the desktop app`. For CLI authentication, support another method such as [cookie import](https://azot.mov/docs/extensions/api.md#authentication).

## `browser.newPage(options?)`

Returns `Promise<BrowserPage>`.

| Option     | Type      | Behavior                                                                            |
| ---------- | --------- | ----------------------------------------------------------------------------------- |
| `title`    | `string`  | Window title. Defaults to the extension title, or `Browser` when none is available. |
| `headless` | `boolean` | The page is hidden by default. Set `false` to show a window for user interaction.   |

Always close the page in `finally`, including when navigation or evaluation fails.

```ts
const page = await browser.newPage({ headless: true });
try {
  await page.goto("https://example.com/video");
  const title = await page.evaluate<string>(() => document.title);
  console.info(title);
} finally {
  await page.close();
}
```

## `page.goto(url, options?)`

Navigates to a URL and waits for page loading to finish or stop. Returns `Promise<void>`, not an HTTP response.

```ts
await page.goto("https://example.com/login", { signal, timeout: 30_000 });
```

Page loading does not guarantee that the website has finished fetching data or updating its DOM.

## `page.evaluate<T = unknown>(script, arg?, options?)`

Runs JavaScript inside the page and returns `Promise<T>`. If the script returns a promise, evaluation awaits it.

A function runs without access to the extension's imports or local variables. Pass a JSON-serializable value through `arg` to provide data. The callback receives it as `unknown`.

```ts
const content = await page.evaluate<string | null>((selector) => {
  if (typeof selector !== "string") throw new TypeError("Expected a selector");
  return document.querySelector(selector)?.textContent ?? null;
}, "h1");
```

A string script is the body of an async function. Use an explicit `return` to retrieve a value. String scripts do not receive `arg`.

```ts
const title = await page.evaluate<string>("return document.title;", undefined, {
  signal,
  timeout: 10_000,
});
```

Use `undefined` for `arg` when only passing options. The type parameter describes the expected result; it does not validate data at runtime. Return serializable data rather than DOM nodes or functions.

Inside evaluation, `window`, `document`, `fetch`, and storage belong to the website. They are separate from the extension's [globals](https://azot.mov/docs/extensions/globals.md).

## `page.waitForURL(url, options?)`

Waits for the current page URL to match a string or `RegExp`. Returns `Promise<void>`. If the URL already matches, it resolves immediately.

```ts
await page.waitForURL(/^https:\/\/example\.com\/account(?:[/?#]|$)/, {
  signal,
  timeout: 10 * 60_000,
});
```

## `page.close()`

Closes the page and copies its session cookies into the extension's `cookieStore`. Returns `Promise<void>`. Closing a page does not clear its saved browser session.

## Timeouts and cancellation

`goto()`, `evaluate()`, and `waitForURL()` accept these options:

| Option      | Type          | Behavior                                                    |
| ----------- | ------------- | ----------------------------------------------------------- |
| `signal`    | `AbortSignal` | Rejects the pending operation when the signal aborts.       |
| `timeout`   | `number`      | Timeout in milliseconds.                                    |
| `timeoutMs` | `number`      | Alias for `timeout`; takes precedence if both are supplied. |

## Cookies and sessions

Pages use a persistent browser session scoped to the extension. Pages from the same extension share that session. Azot seeds it from the extension's `cookieStore` when opening a page.

After successful `goto()`, `waitForURL()`, and `close()` calls, Azot copies browser cookies into `cookieStore`, where they are available to the extension's `fetch()`.

## Interactive login

Use a visible page in `auth.login()` and wait for the service's post-login URL.

```ts
import { browser, defineProvider } from "azot";

defineProvider({
  matches: ["https://example.com/*"],
  list: ({ url }) => listEntries(url),
  auth: {
    methods: ["interactive", "cookies"],

    async getState() {
      const response = await fetch("https://example.com/api/me");
      if (response.status === 401 || response.status === 403) {
        return { authenticated: false };
      }
      if (!response.ok) throw new Error("Could not verify the session");
      return { authenticated: true };
    },

    async login(request) {
      // Imported cookies are verified by getState() after login() returns.
      if (request.method !== "interactive") return;

      const signal = Azot.signal;
      const page = await browser.newPage({ title: "Sign in to Example", headless: false, signal });
      try {
        await page.goto("https://example.com/login", { signal });
        await page.waitForURL(/^https:\/\/example\.com\/account(?:[/?#]|$)/, {
          signal,
          timeout: 10 * 60_000,
        });
      } finally {
        await page.close();
      }
    },
  },
});
```

Replace the example URLs and session check with the service's own endpoints and authentication rules. See [Authentication](https://azot.mov/docs/extensions/api.md#authentication) for the other login methods and `auth.getState()`.
