ScreenshotNeo

BlogHow-to

How to Use BrowserCat to Generate Social Media Preview Images from a URL

Use BrowserCat and Playwright to capture a URL as a social preview image, choose the right screenshot mode, and troubleshoot common capture issues.

By the ScreenshotNeo team4 October 20268 min read

Use BrowserCat’s managed browser with Playwright: connect to its WebSocket endpoint using an API key, navigate to the page, wait for the content you need, set a deliberate viewport, and save a screenshot. The example below creates a PNG preview from a URL. Its 1200 × 630 viewport is only an example composition; verify the current requirements of the social network where you plan to use the image.

1. Set up BrowserCat and Playwright

BrowserCat’s quick start demonstrates Playwright and a connection to wss://api.browsercat.com/connect authenticated with an Api-Key header. Keep the key in an environment variable or secret manager. Do not place it in browser-delivered JavaScript, commit it to source control, or include it in logs. BrowserCat recommends Playwright as a starting library and also describes support for Puppeteer and CDP-based clients; those are vendor claims, not independent compatibility tests. See the BrowserCat quick start.

Install Playwright in a Node.js project:

npm install playwright

Set the key in your shell, then run the script with the target URL:

export BROWSERCAT_API_KEY="your_api_key"
node capture-preview.mjs "https://example.com"

2. Capture a URL as a preview image

Save this as capture-preview.mjs. It accepts the URL as an argument, uses a fixed viewport, waits for the page load event, optionally waits for a page-specific selector, and writes a PNG file.

import { chromium } from 'playwright';

const targetUrl = process.argv[2];
if (!targetUrl) {
  console.error('Usage: node capture-preview.mjs <url>');
  process.exit(2);
}
if (!process.env.BROWSERCAT_API_KEY) {
  console.error('Set BROWSERCAT_API_KEY in the environment.');
  process.exit(2);
}

const browser = await chromium.connect('wss://api.browsercat.com/connect', {
  headers: { 'Api-Key': process.env.BROWSERCAT_API_KEY },
});

try {
  const page = await browser.newPage();
  // Example dimensions only. Check the destination platform's current guidance.
  await page.setViewportSize({ width: 1200, height: 630 });
  await page.goto(targetUrl, { waitUntil: 'load' });

  // Optional: wait for the content that must appear in the image.
  // Replace this selector with one from the target page, or remove the line.
  // await page.locator('main h1').waitFor({ state: 'visible', timeout: 10000 });

  await page.screenshot({ path: 'preview.png', type: 'png' });
  console.log('Saved preview.png');
} finally {
  await browser.close();
}

The basic flow follows BrowserCat’s documented connection, navigation, wait, and screenshot mechanics. Playwright’s screenshot controls determine the capture details. A successful screenshot only confirms that an image was produced; it does not confirm that a social network will display it as intended.

3. Choose what to capture

Viewport screenshot for a composed preview

For a fixed landscape composition, set the viewport before navigating or capturing, then take a regular page screenshot. The visible viewport determines the captured area. Inspect the result at its intended dimensions and adjust the viewport and page state if important content is cropped.

Full page for a long document

Use fullPage: true when you need the entire page. A full-page capture can be much taller than a typical social preview composition, so it is usually the wrong choice when you need a compact card.

await page.screenshot({ path: 'full-page.png', fullPage: true });

Element screenshot for a hero or card

If the page contains a dedicated hero or preview region, capture that element instead of the whole viewport. Use a selector that uniquely identifies the intended region.

await page.locator('.hero-card').screenshot({ path: 'hero.png' });

PNG, JPEG, clipping, masks, and styling

  • PNG: the default demonstrated format; useful when you want a lossless capture.
  • JPEG: available with a quality setting. Check how compression affects gradients, text edges, and file size for your image.
  • Clipping: capture a defined rectangle when you need a specific crop.
  • Masks: visually cover selected elements in a screenshot. A mask is not a substitute for ensuring sensitive information never appears in the rendered page.
  • Custom styles: Playwright supports stylesheet or style injection for capture presentation. This changes the rendered appearance; it does not rewrite the page’s social metadata.

BrowserCat’s Playwright cheatsheet documents viewport sizing, full-page and locator screenshots, clipping, masks, styling, PNG, and JPEG options. Use the options that fit the composition you need, and review the produced file rather than assuming the capture matches the destination’s display.

4. Wait for the content that matters

waitUntil: 'load' waits for the page load event, but client-rendered content, late-loading images, and animations may still affect the screenshot. For a reliable capture, wait for a meaningful page-specific condition, such as a visible title or hero image. Avoid adding an arbitrary long delay as the only readiness check: it can make every capture slower and still fail to cover unpredictable loading.

await page.goto(targetUrl, { waitUntil: 'load' });
await page.locator('.hero-card img').waitFor({ state: 'visible', timeout: 10000 });
await page.screenshot({ path: 'preview.png' });

If the desired image itself loads asynchronously, visibility alone may not mean the image is decoded. Where needed, wait for the image element’s complete state and nonzero natural dimensions, using a selector specific to the page. Set a bounded timeout and surface a useful error if the required content never appears.

5. Verify the image against the destination

  1. Open the generated file and check that the main subject is visible, text is legible at the intended display size, and no transient overlay obscures the composition.
  2. Confirm the output dimensions and file type using your image tools or file metadata.
  3. Check the target social network’s current official image guidance and preview/debugging workflow. This guide does not assert platform-specific dimensions or file-size limits.
  4. Test the actual page URL with that platform’s current preview tool. The screenshot is a rendered image; it does not change the page’s Open Graph or other metadata.

6. Configuration and connection choices

BrowserCat’s configuration overview says settings can be supplied as query parameters or through the BrowserCat-Opts header, with header keys taking precedence when both are set. It includes browser and proxy configuration examples. These settings are not needed for the basic screenshot flow; use them only when your capture has a concrete browser or network requirement, and confirm current syntax in the BrowserCat configuration documentation.

Choose among Playwright, Puppeteer, or a CDP-based client based on the automation library already used by your project and the operations you need. BrowserCat’s documentation recommends Playwright for getting started and shows the conceptual change from launching a local browser to connecting to BrowserCat. No performance or compatibility comparison is implied here.

7. Performance, reliability, and cost considerations

  • Keep captures focused: a viewport or one element is usually less work than a full-page capture when a compact preview is the goal.
  • Wait specifically: waiting for the title or hero image can avoid both premature captures and unnecessary fixed delays. Bound waits so a missing selector does not stall a job indefinitely.
  • Handle failures explicitly: distinguish navigation errors, timeouts, missing selectors, and file-write errors in logs. Retry only failures that may be transient, and avoid unbounded retries.
  • Protect the key: store credentials in environment secrets, rotate them according to your organization’s practice, and redact authorization data from diagnostics.
  • Budget from current terms: the research sources reviewed for this guide do not establish BrowserCat pricing, quotas, or concurrency limits. Check BrowserCat’s current service terms and account details before estimating production cost or throughput.

8. Troubleshooting

Symptom Likely cause Fix
WebSocket connection is rejected The API key is missing, invalid, or sent under the wrong header name. Confirm BROWSERCAT_API_KEY is set and send it as Api-Key. Keep the secret out of client-side code.
The page is blank or incomplete The capture happened before client-rendered content or images were ready, or the page itself did not render successfully. Check navigation and page errors, then wait for the specific title, hero, or image state needed in the capture.
The screenshot is the wrong size The viewport was not set as expected, or a full-page/element capture was used instead of a viewport capture. Set the viewport explicitly and choose regular, full-page, or locator capture deliberately. Inspect the saved file dimensions.
The image omits the target section The section is outside the viewport, hidden, or matched by an incorrect selector. Use the correct element selector or adjust the viewport and scroll state before taking the screenshot.
Capture times out waiting for a selector The selector does not exist on this URL, appears only under another state, or loads too slowly. Verify the selector on the page, make the wait conditional when pages differ, and use a bounded timeout with a useful error.
Preview differs from what the social network displays The network may use page metadata and its own crawler or cache rather than your generated screenshot. Use the network’s current preview/debugging workflow and check the page’s relevant metadata separately.
Local run cannot resolve Playwright The package is missing or the script is run outside the project where it was installed. Install playwright in the project and run the script from that project environment.

9. Or skip the browser setup

ScreenshotNeo is a website screenshot API and MCP server from Yorker Media. Its API can return a PNG, JPEG, WebP, or PDF from one GET request. See the ScreenshotNeo API documentation.

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
import requests
r = requests.get("https://api.screenshotneo.com/v1/shot", params={"access_key": "YOUR_API_KEY", "url": "https://stripe.com"}, timeout=90)
open("shot.webp", "wb").write(r.content)
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);

ScreenshotNeo removes cookie banners, newsletter popups, and chat widgets before the shot; bot checks, blank pages, and failed loads are never billed. Its MCP server lets AI agents take screenshots. The free plan includes 1,000 screenshots a month with no card, and paid plans start at $5 for 3,000. Sign up for free and try ScreenshotNeo.

FAQ

Does this screenshot set a page’s social preview metadata?

No. It creates an image file. Social networks generally determine link previews from the page and their own systems; check the destination’s current documentation and preview tool.

Can I use the same script for many URLs?

Yes. Pass each URL to the capture flow and give each output a distinct filename. Add bounded concurrency and failure handling appropriate to your workload, and confirm the current BrowserCat service limits before scaling.

Should I use a full-page screenshot for a social card?

Only when the desired asset is intentionally a long page image. For a compact preview composition, use the viewport or a specific element.