ScreenshotNeo

BlogHow-to

How to Capture Mobile Website Screenshots with PhantomJS

Set a mobile viewport, user agent, readiness check and capture rectangle in PhantomJS, with runnable code, limits, fixes and a hosted alternative.

By the ScreenshotNeo team30 September 20268 min read

How to Capture Mobile Website Screenshots with PhantomJS

Direct answer: Create a PhantomJS webpage, set page.viewportSize to a phone-sized CSS viewport, optionally set a mobile user agent before opening the URL, call page.render() after a successful page.open(), then exit. This produces a repeatable responsive-width screenshot; it does not emulate every hardware and browser characteristic of a current iPhone or Android device.

PhantomJS is a headless browser controlled from JavaScript and the phantomjs command-line executable. The official documentation describes page.viewportSize for the browser viewport, page.clipRect for the capture rectangle, and page.render() for writing an image or PDF. The latest-release documentation identifies PhantomJS 2.1.1, so treat it as legacy browser software when you assess compatibility. See the official screen-capture guide, viewport reference, and render reference.

1. Install PhantomJS and create a capture script

Install the PhantomJS 2.1.1 executable using the package method appropriate for your operating system, then verify that it is on your path:

A PhantomJS script sets the viewport, opens the page, waits for readiness and renders the image.
A PhantomJS script sets the viewport, opens the page, waits for readiness and renders the image.
phantomjs --version

Save this as capture-mobile.js:

var page = require('webpage').create();

// CSS viewport dimensions. These control responsive layout breakpoints.
page.viewportSize = { width: 390, height: 844 };

// Set this before page.open() when the server uses the user agent
// to select mobile markup or redirects.
page.settings.userAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1';

page.open('https://example.com/', function (status) {
  if (status !== 'success') {
    console.log('Unable to load the page');
    phantom.exit(1);
    return;
  }

  page.render('mobile.png');
  phantom.exit();
});

Run it with:

phantomjs capture-mobile.js

The output filename selects the format. A .png or .jpg filename is the usual choice. PhantomJS render documentation also lists PDF, BMP and PPM; GIF availability depends on the Qt build.

2. Choose mobile viewport dimensions

page.viewportSize is the layout viewport, measured in CSS pixels. It determines which responsive CSS rules match. Pick a width and height that represent the scenario you are reviewing, then keep those values fixed in automated jobs.

Use case Example viewport What it tells you
Narrow phone layout 390 × 844 Common single-column breakpoints and first-screen content
Small Android-like layout 360 × 800 Wrapping and overflow at a tighter width
Landscape phone check 844 × 390 Horizontal navigation and landscape breakpoints
Tablet-width check 768 × 1024 Intermediate responsive layout

These are illustrative CSS dimensions, not official device presets. A narrow viewport alone does not change the browser engine, add touch input, or reproduce a handset’s device-pixel ratio.

3. Set a mobile user agent when the server needs it

Some applications inspect the user-agent header and send different HTML, redirects or feature flags. Set page.settings.userAgent before page.open(); the settings reference says these settings take effect during the initial open call.

page.settings.userAgent = 'Mozilla/5.0 (Linux; Android 13; Pixel 7) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0 Mobile Safari/537.36';
page.open('https://example.com/', callback);

Changing the string does not turn PhantomJS into Chrome or Safari. It only changes what the server sees. Use a user agent when you are testing server-side mobile branching; omit it when you want to inspect the same markup desktop clients receive at a narrow viewport.

4. Capture a defined rectangle with clipRect

page.clipRect limits the rendered area to an x, y, width and height rectangle. This is useful for a hero, a card, or a fixed first-screen image.

page.clipRect = { x: 0, y: 0, width: 390, height: 844 };

Set it before rendering. A viewport render is not automatically a guaranteed full-document capture. If you need the entire page, inspect the page’s dimensions and choose bounds that cover the content, then verify the output. A simple viewport screenshot is safer when you need exactly one phone-sized screen.

5. Wait for asynchronous content

The official examples render inside the successful page.open() callback. That is sufficient for pages whose content is ready at navigation completion. Modern applications often fetch data or hydrate components afterward, so define a site-specific readiness condition and verify the result.

Use page.evaluate() to read serializable DOM state from the page context:

function waitFor(selector, done, deadline) {
  var started = Date.now();
  var timer = setInterval(function () {
    var present = page.evaluate(function (sel) {
      return !!document.querySelector(sel);
    }, selector);
    if (present) {
      clearInterval(timer);
      done();
    } else if (Date.now() - started > deadline) {
      clearInterval(timer);
      console.log('Readiness timeout: ' + selector);
      done();
    }
  }, 100);
}

page.open('https://example.com/', function (status) {
  if (status !== 'success') {
    phantom.exit(1);
    return;
  }
  waitFor('.product-grid', function () {
    page.render('mobile.png');
    phantom.exit();
  }, 10000);
});

This checks for a known element rather than assuming one fixed delay works for every site. page.evaluate() executes in a sandboxed page context and returns serializable values; it is a DOM-state tool, not a device-emulation mechanism. See the evaluate reference.

6. Full example with status, readiness and a clip

var page = require('webpage').create();
page.viewportSize = { width: 390, height: 844 };
page.clipRect = { x: 0, y: 0, width: 390, height: 844 };
page.settings.userAgent = 'Mozilla/5.0 (iPhone; CPU iPhone OS 17_0 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/17.0 Mobile/15E148 Safari/604.1';

function renderAndExit() {
  page.render('mobile.png');
  phantom.exit(0);
}

page.open('https://example.com/', function (status) {
  if (status !== 'success') {
    console.log('Unable to load the page: ' + status);
    phantom.exit(1);
    return;
  }
  // Replace this with a selector your application renders after its data load.
  var ready = page.evaluate(function () {
    return document.body && document.body.innerText.length > 0;
  });
  if (ready) {
    renderAndExit();
  } else {
    renderAndExit();
  }
});

Keep the explicit status check even in small scripts. Rendering after a failed open can create a misleading blank artifact.

7. What PhantomJS can and cannot emulate

  • It can: change the CSS viewport, send a chosen user-agent string, select a capture rectangle, run page JavaScript, and render PNG, JPEG and other documented formats.
  • It does not document: a device-pixel-ratio control, touch-event emulation, or a switch that reproduces a current iPhone or Android browser engine.
  • Therefore: describe the result as a mobile-width or responsive screenshot. Validate separately when your feature depends on touch gestures, high-density rendering, browser-specific APIs, or current mobile engine behavior.

8. Troubleshooting

Symptom Likely cause Fix
“Unable to load the page” DNS, TLS, redirect or network failure Log the callback status, verify the URL from the same machine, and exit non-zero instead of rendering.
Desktop layout at phone width Server branches on user agent or the page lacks responsive CSS Set a mobile user agent before page.open(); inspect the source and breakpoints.
Blank or incomplete screenshot App content loads after navigation Wait for a known selector or application state with page.evaluate(), then render.
Important content is cut off clipRect is smaller than the intended region Remove the clip for a viewport shot or calculate and verify a larger rectangle.
Expected device realism is missing Viewport and user agent are only partial controls Use a current browser automation stack when touch, DPR or engine fidelity is required.
GIF output fails Qt build lacks GIF support Use PNG or JPEG, or confirm the capabilities of the PhantomJS build.

9. Performance, reliability and cost considerations

For repeatable jobs, reuse one script template and vary URL, viewport, user agent and output path. Keep readiness checks bounded so a broken page cannot hold a worker forever. Record the URL, viewport, user agent, status and output filename with each artifact. Compare screenshots at the same dimensions and format to reduce noisy diffs.

ScreenshotNeo removes common consent banners, popups and chat widgets before capture.
ScreenshotNeo removes common consent banners, popups and chat widgets before capture.

PhantomJS is a legacy engine. A successful render proves that PhantomJS loaded and painted the page; it does not prove that current mobile browsers will render it identically. For high-value pages, compare a PhantomJS image with a capture from a current browser engine before treating a visual difference as a product defect.

PhantomJS itself has no hosted per-screenshot billing in this workflow: you run the executable and pay for your own compute, storage and network. Your operational costs rise with concurrency, page weight, fonts and third-party resources. Block unnecessary resources only if your test remains representative; otherwise you may hide the very layout problem you want to find.

Or skip the browser setup

ScreenshotNeo provides a hosted screenshot API and MCP server. It accepts one GET request and returns PNG, JPEG, WebP or PDF. Cookie and consent banners are accepted and 60+ known consent platforms, newsletter popups and chat widgets are removed before capture; each step can be turned off. Bot checks, blank pages, timeouts, failed loads and cache hits are not billed, and the response identifies the result with X-Page-Verdict and X-Billed headers.

See the ScreenshotNeo API documentation for the full option list. A mobile-width capture can be as simple as:

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}`);

Set viewport dimensions, device presets or any of the 63 options for full-page capture with lazy images, element selectors, dark mode, retina scale, custom CSS and JavaScript, clicks, waits, blocked resources, headers, cookies, authorization, timezone, geolocation, transparency, resizing and caching. You can also submit asynchronous jobs with signed webhooks, capture up to 100 URLs per bulk call, generate PDFs, use signed links in public <img> tags, and query usage. An MCP server exposes take_screenshot, get_page_info and capture_pdf to Claude, Cursor and other MCP clients.

The Free plan includes 1,000 shots per month with no card. Paid plans start at $5 for 3,000 shots; yearly billing gives two months free, and every feature is on every plan. Create a free ScreenshotNeo account.

10. FAQ

Does a mobile user agent make PhantomJS an iPhone simulator?

No. It can influence server responses, but the documented controls do not include touch, device-pixel-ratio or current mobile-engine emulation.

Should I set clipRect for every screenshot?

No. Use it for a defined region. Omit it when the viewport itself is the region you want.

Why does my screenshot miss data loaded by JavaScript?

Navigation completed before the application finished rendering. Wait for a selector or other known state, with a bounded timeout, before calling page.render().

Which output format should I choose?

Use PNG for lossless visual diffs, JPEG for smaller photographic images, WebP through a hosted service that supports it, and PDF when the deliverable is a document.

When should I replace PhantomJS?

Use a current browser automation system when touch behavior, modern APIs, high-density rendering or browser-engine parity is part of the requirement.