How to connect to an open tab in an existing browser
Overview
This guide demonstrates how to connect to an open browser tab and execute AgentQL queries within it using WebSocket connections.
Why access an open browser tab?
Connecting to open browser tabs offers several benefits:
- Interactive development: Test queries in real-time while viewing the browser.
- Debugging: Conveniently inspect and troubleshoot query behavior.
- Session preservation: Work with existing login states and cookies.
- Manual preparation: Allows manual setup of complex page states before automation.
Connecting to an open tab
Close Google Chrome if it's open.
The following example shows how to connect to an open browser tab.
You'll need to replace WEBSOCKET_URL
with the actual WebSocket URL obtained from the preceding command.
js
const { chromium } = require('playwright');
const { wrap } = require('agentql');
configure({ apiKey: process.env.AGENTQL_API_KEY });
// Connect to an open browser tab via WebSocket URL
const WEBSOCKET_URL = 'ws://localhost:9222/devtools/browser/...'; // Your actual WebSocket URL
const URL = 'https://scrapeme.live/shop';
// Execute your query
const STOCK_QUERY = `
{
number_in_stock
}
`;
async function interactWithNewPageInLocalBrowser() {
// Connect to the browser via Chrome DevTools Protocol
const browser = await chromium.connectOverCDP(WEBSOCKET_URL);
// Create a new tab in the browser window and wrap it to get access to the AgentQL's querying API
const context = browser.contexts()[0];
const page = wrap(await context.newPage());
await page.goto(URL);
// Use queryElements() method to locate the search product box from the page
const response = await page.queryElements(SEARCH_QUERY);
// Use Playwright's API to fill the search box and press Enter
await response.search_products_box.type('Charmander');
await page.keyboard.press('Enter');
// Use queryData() method to fetch the stock number from the page
const stockResponse = await page.queryData(STOCK_QUERY);
console.log(stockResponse);
await browser.close();
}
interactWithNewPageInLocalBrowser().catch(console.error);
Related content
Playwright Browsers
Official Playwright documentation for handling different browser contexts, working with multiple pages, network interception and modification.
Python example script
This Python script demonstrates how to interact with an external or existing browser with AgentQL.
JavaScript example script
This JavaScript script demonstrates how to interact with an external or existing browser with AgentQL.