> For the complete documentation index, see [llms.txt](https://developers.oxylabs.io/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://developers.oxylabs.io/products/pt-br/agent-browser/manipulador-de-paginas.md).

# Manipulador de páginas

Deixe o Agent Browser identificar cada página, lidar automaticamente com desafios de acesso e informar ao seu script quando a página estiver pronta.

{% hint style="warning" %}
**Acesso à conta necessário:** contas sem o recurso habilitado recebem `o manipulador de página 400 não está habilitado para esta conta no handshake` (veja [Códigos de resposta](/products/pt-br/agent-browser/codigos-de-resposta.md)).
{% endhint %}

Oxylabs Agent Browser usa um manipulador de página integrado para desafios de acesso a sites. O `page_handler` parâmetro identifica cada página que carrega, conclui os desafios suportados que encontra e informa o estado da página ao seu script como uma mensagem da janela.

```bash
wss://USER:PASS@hb.oxylabs.io?p_cc=US&page_handler=true
```

**O manipulador de página está desabilitado por padrão** e deve ser passado para cada conexão e mantido idêntico para todas as conexões com o mesmo destino, incluindo cada execução que compartilha um [perfil persistente](/products/pt-br/agent-browser/persistent-sessions-and-profiles.md#persistent-profiles) (perfil `o_profile` ou uma sessão sticky de proxy `proxy_resi_ses_id`).

<table><thead><tr><th width="133">Parâmetro</th><th width="405">Descrição</th><th width="93.5">Tipo</th></tr></thead><tbody><tr><td><code>page_handler</code></td><td>Habilita a identificação de páginas e o tratamento automático de desafios. Padrão: <code>false</code>.</td><td>booleano</td></tr></tbody></table>

{% hint style="info" %}
O manipulador de página adiciona tempo aos carregamentos de página, então habilite-o apenas para alvos que exibem desafios. Se o recurso não estiver habilitado para sua conta, entre em contato com [suporte da Oxylabs.](mailto:support@oxylabs.io)
{% endhint %}

## Status da página

Com o manipulador de página habilitado, o navegador relata o status de cada página como uma `janela` mensagem:

```javascript
{ source: "oxylabs-runtime", type: "oxylabs-page-status", status: "open" }
```

<table><thead><tr><th width="130.5">Status</th><th>Descrição</th></tr></thead><tbody><tr><td><code>identificando</code></td><td>A página está sendo verificada.</td></tr><tr><td><code>fechado</code></td><td>Um desafio foi encontrado e está sendo tratado. A página ainda não pode ser usada.</td></tr><tr><td><code>aberto</code></td><td>A página está pronta para uso.</td></tr><tr><td><code>falhou</code></td><td>O desafio não pôde ser concluído. A mensagem inclui um <code>erro</code> campo.</td></tr></tbody></table>

`identificando` e `fechado` são temporários, então aguarde `aberto` ou `falhou`. Uma página sem desafio informa `aberto` cerca de 8 segundos após o carregamento, e o tratamento de um desafio normalmente leva 30–45 segundos. Se o status for `falhou`, feche a sessão e tente novamente com uma nova conexão.

## Monitorando o status da página

A saída do console do navegador não é entregue aos clientes CDP, então escute a mensagem da janela com um script adicionado antes de a página carregar e, em seguida, aguarde o status final:

{% tabs %}
{% tab title="Python (Playwright)" %}

```python
from playwright.sync_api import sync_playwright

username = "USERNAME"
password = "PASSWORD"
endpoint = "hb.oxylabs.io"
browser_url = f"wss://{username}:{password}@{endpoint}?p_cc=US&page_handler=true"

# Keep the latest page status in the page
status_listener = """
window.addEventListener("message", (e) => {
  const d = e.data;
  if (d?.source === "oxylabs-runtime" && d.type === "oxylabs-page-status") {
    window.__pageStatus = d.status;
  }
});
"""

with sync_playwright() as p:
    browser = p.chromium.connect_over_cdp(browser_url)
    context = browser.contexts[0] if browser.contexts else browser.new_context()
    context.add_init_script(status_listener)  # add before opening the page
    page = context.new_page()
    page.goto("https://example.com")

    # Wait until the page is ready ("open") or the handler gives up ("failed")
    page.wait_for_function("['open', 'failed'].includes(window.__pageStatus)", timeout=90000)
    print(page.evaluate("window.__pageStatus"), page.title())
    browser.close()
```

{% endtab %}

{% tab title="JavaScript (Playwright)" %}

```javascript
import { chromium } from "playwright";

const username = "USERNAME";
const password = "PASSWORD";
const endpoint = "hb.oxylabs.io";
const browserUrl = `wss://${username}:${password}@${endpoint}?p_cc=US&page_handler=true`;

// Keep the latest page status in the page
const statusListener = () => {
    window.addEventListener("message", (e) => {
        const d = e.data;
        if (d?.source === "oxylabs-runtime" && d.type === "oxylabs-page-status") {
            window.__pageStatus = d.status;
        }
    });
};

(async () => {
    const browser = await chromium.connectOverCDP(browserUrl);
    const context = browser.contexts()[0] || (await browser.newContext());
    await context.addInitScript(statusListener); // add before opening the page
    const page = await context.newPage();
    await page.goto("https://example.com");

    // Wait until the page is ready ("open") or the handler gives up ("failed")
    await page.waitForFunction(
        () => ["open", "failed"].includes(window.__pageStatus),
        null,
        { timeout: 90000 }
    );
    console.log(await page.evaluate(() => window.__pageStatus), await page.title());
    await browser.close();
})();
```

{% endtab %}

{% tab title="JavaScript (Puppeteer)" %}

```javascript
import puppeteer from "puppeteer";

const username = "USERNAME";
const password = "PASSWORD";
const endpoint = "hb.oxylabs.io";
const browserUrl = `wss://${username}:${password}@${endpoint}?p_cc=US&page_handler=true`;

// Keep the latest page status in the page
const statusListener = () => {
    window.addEventListener("message", (e) => {
        const d = e.data;
        if (d?.source === "oxylabs-runtime" && d.type === "oxylabs-page-status") {
            window.__pageStatus = d.status;
        }
    });
};

(async () => {
    const browser = await puppeteer.connect({ browserWSEndpoint: browserUrl });
    const page = await browser.newPage();
    await page.evaluateOnNewDocument(statusListener); // add before opening the page
    await page.goto("https://example.com");

    // Wait until the page is ready ("open") or the handler gives up ("failed")
    await page.waitForFunction(
        () => ["open", "failed"].includes(window.__pageStatus),
        { timeout: 90000 }
    );
    console.log(await page.evaluate(() => window.__pageStatus), await page.title());
    await browser.close();
})();
```

{% endtab %}
{% endtabs %}

### Tratando desafios após o carregamento da página

O manipulador de página lida com desafios presentes quando uma página carrega. Um desafio que aparece depois, por exemplo após um clique ou o envio de um formulário, não é tratado automaticamente. Para tratá-lo, envie uma `oxylabs-page-handle` mensagem para a página. O navegador verifica a página novamente, trata qualquer desafio que encontrar e informa o status como antes.

### Servidor MCP e Habilidades do Agente

Se você estiver usando um agente de IA ou um assistente de codificação, recomendamos fortemente aproveitar nossos métodos simples de integração para o Oxylabs Agent Browser:

<table data-header-hidden><thead><tr><th width="152"></th><th></th></tr></thead><tbody><tr><td><a href="/ai-workflows/agent-skills.md"><strong>Habilidades do Agente</strong></a></td><td>Configure o Agent Browser no Claude Code, Cursor e outros assistentes de codificação com IA.</td></tr><tr><td><a href="/ai-workflows/mcp.md"><strong>Servidor MCP</strong></a></td><td>Dê aos assistentes de IA compatíveis com MCP um Agent Browser remoto.</td></tr></tbody></table>


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://developers.oxylabs.io/products/pt-br/agent-browser/manipulador-de-paginas.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
