ScreenshotNeo

BlogHow-to

How to Capture iPhone-Sized Website Screenshots with PhantomJS

Set a narrow PhantomJS viewport, wait for the page, and render an iPhone-sized screenshot with clipping, user-agent options, and practical fixes.

By the ScreenshotNeo team30 September 20269 min read

How to Capture iPhone-Sized Website Screenshots with PhantomJS

To capture an iPhone-sized website screenshot with PhantomJS, set page.viewportSize to the width and height you need before opening the URL, then call page.render() after the page has loaded. Use page.clipRect when the output should contain only a specific rectangle.

The example below uses a 375 × 667 viewport, a common narrow mobile test size. Those numbers are test dimensions, not a claim that PhantomJS reproduces a particular iPhone model. PhantomJS documents viewport sizing and user-agent configuration, but not complete iPhone hardware or Safari emulation. Its project homepage also states that development is suspended, so treat this as a legacy workflow for existing scripts.

What “iPhone-sized” means in PhantomJS

There are three settings and concepts to keep separate:

  • Viewport size: page.viewportSize controls the browser area used for responsive layout calculations.
  • Clip rectangle: page.clipRect controls the rectangle written to the image. It can match the viewport for a first-screen capture or be larger or smaller for a custom crop.
  • User agent: page.settings.userAgent can influence server-side content selection. It does not create full device emulation, touch events, or current Safari rendering.

PhantomJS runs on QtWebKit, and the official project homepage says, “Important: PhantomJS development is suspended until further notice.” Modern CSS, JavaScript, TLS, bot checks, and browser APIs may therefore behave differently from a current iPhone browser. See the PhantomJS project homepage and the official page automation guide for the documented scope.

Prerequisites and a minimal capture script

You need a PhantomJS executable available on your PATH and a JavaScript file. Save this as iphone-shot.js:

The viewport controls responsive layout while the clipping rectangle controls the captured area.
The viewport controls responsive layout while the clipping rectangle controls the captured area.
var page = require('webpage').create();

page.viewportSize = {
  width: 375,
  height: 667
};

page.clipRect = {
  top: 0,
  left: 0,
  width: 375,
  height: 667
};

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

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

Run it with:

phantomjs iphone-shot.js

The script follows the sequence shown in PhantomJS’s official screen-capture example: create a webpage, assign the viewport, open the URL, check the status, render, and exit. Set the viewport and other initial settings before page.open().

Choose dimensions for your test

Change the width and height to match the breakpoint or test case you care about:

page.viewportSize = { width: 320, height: 568 }; // narrow layout
// or
page.viewportSize = { width: 375, height: 812 }; // taller narrow layout
// or
page.viewportSize = { width: 414, height: 896 }; // wider narrow layout

Viewport dimensions are CSS pixels. A retina display scale is not documented as part of PhantomJS’s viewport API, so a 375-pixel viewport does not automatically produce a 750-pixel, two-times-density image. If you need a particular output pixel size, set the capture rectangle deliberately and inspect the resulting file.

Viewport-sized versus full-page output

With clipRect equal to the viewport, the output is limited to the first 375 × 667 pixels. To capture a taller area, increase the clip height:

page.viewportSize = { width: 375, height: 667 };
page.clipRect = { top: 0, left: 0, width: 375, height: 1600 };

This changes the screenshot bounds; it does not guarantee that every lazy-loaded image below the fold has been fetched. PhantomJS’s screen-capture documentation explains the distinction between viewport and clipping rectangle. For long pages, scroll or trigger the page’s lazy-loading code before rendering, then allow the resulting resources to finish loading.

Wait for delayed content before rendering

A successful page.open callback means the navigation completed according to PhantomJS, not that every asynchronous component has finished. A short timer can help with pages that add content after load:

var page = require('webpage').create();
page.viewportSize = { width: 375, height: 667 };
page.clipRect = { top: 0, left: 0, width: 375, height: 667 };

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

  window.setTimeout(function () {
    page.render('after-wait.png');
    phantom.exit();
  }, 1000);
});

The official homepage uses a brief delay in an example, but no single delay works for every site. Prefer a page-specific readiness signal when you control the application. You can poll for an element with page.evaluate() and a timer, or expose a flag from the page when its data has rendered. Keep the wait finite so a broken page cannot leave a batch job running forever.

Set a mobile user agent when the site serves different markup

Some servers choose templates from the user-agent string. Set it before the initial open:

var page = require('webpage').create();
page.viewportSize = { width: 375, height: 667 };
page.settings.userAgent =
  'Mozilla/5.0 (iPhone; CPU iPhone OS 15_0 like Mac OS X) ' +
  'AppleWebKit/605.1.15 (KHTML, like Gecko) Version/15.0 ' +
  'Mobile/15E148 Safari/604.1';

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

PhantomJS’s settings reference says settings apply during the initial page.open call. Changing the user agent after navigation will not retroactively change the first request. A mobile-looking string may change server-side content, but it does not emulate iPhone touch behavior, hardware metrics, Safari bugs, or WebKit versions.

Control JavaScript, images, and timeouts

The settings object includes controls that matter for screenshot reliability. JavaScript and image loading are enabled by default. A resource timeout can stop a page that never finishes responding:

var page = require('webpage').create();
page.viewportSize = { width: 375, height: 667 };
page.settings.javascriptEnabled = true;
page.settings.loadImages = true;
page.settings.resourceTimeout = 30000;

page.onResourceError = function (error) {
  console.log('Resource error: ' + error.url + ' (' + error.errorCode + ')');
};

page.open('https://example.com/', function (status) {
  if (status !== 'success') {
    console.log('Open failed: ' + status);
    phantom.exit(1);
    return;
  }
  page.render('configured.png');
  phantom.exit();
});

Disabling JavaScript can make a static page easier to capture, but it also removes client-rendered content. Disabling images produces a faster, incomplete visual and is useful only when you are intentionally testing a text-only fallback.

Output formats and image quality

page.render() selects the output from the filename extension. The documented formats include PNG, JPEG, BMP, PPM, and PDF; GIF support depends on the Qt build. Use PNG when you need lossless pixels or crisp text. Use JPEG when a smaller file matters and some compression is acceptable:

page.render('shot.png');
page.render('shot.jpg');
page.render('shot.pdf');

PhantomJS’s render API documentation describes JPEG quality and PNG compression options. Configure those options in the page settings supported by your PhantomJS build, and verify the generated file in the same build used by your deployment.

Capture a particular element

PhantomJS does not provide a selector argument to render(). Find an element’s bounding box in the page, then assign that rectangle to clipRect:

var page = require('webpage').create();
page.viewportSize = { width: 375, height: 667 };

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

  var box = page.evaluate(function () {
    var node = document.querySelector('.hero');
    if (!node) return null;
    var r = node.getBoundingClientRect();
    return {
      left: r.left + window.pageXOffset,
      top: r.top + window.pageYOffset,
      width: r.width,
      height: r.height
    };
  });

  if (!box) {
    console.log('Element not found');
    phantom.exit(1);
    return;
  }

  page.clipRect = box;
  page.render('hero.png');
  phantom.exit();
});

Account for fixed headers, page scroll offsets, fractional coordinates, and elements that change size after fonts or images load. If the element is below the fold, scroll to it first or use document coordinates as shown.

Common errors and fixes

Symptom Likely cause Fix
Desktop layout in the image Viewport was set after page.open, or the site uses server-side detection. Assign viewportSize and, if needed, userAgent before opening.
Image is the wrong size clipRect differs from the intended bounds. Set explicit top, left, width, and height.
Blank or half-rendered page Rendering happened before asynchronous content completed. Wait for a readiness condition or a bounded delay; keep images and JavaScript enabled when required.
“Unable to load the page” DNS, TLS, network, redirect, or server failure. Log the callback status and resource errors, test the URL from the capture host, and check redirects and certificates.
Modern page throws script errors PhantomJS’s old QtWebKit engine lacks newer browser APIs. Use a compatibility build only for legacy work, simplify the page under test, or move capture to a current browser engine.
Content differs from an iPhone User-agent and viewport are being mistaken for device emulation. Describe the result as a narrow viewport capture, not a hardware-accurate iPhone screenshot.
Long batch jobs hang A request never completes or a script waits forever. Set resourceTimeout, enforce a process-level timeout, and always call phantom.exit().
A hosted capture can remove common overlays before producing the final image.
A hosted capture can remove common overlays before producing the final image.

Performance, reliability, and cost considerations

  • Reuse a process carefully: Opening several pages in one PhantomJS process can reduce startup overhead, but clear page state between jobs and always close the process on fatal errors.
  • Keep captures bounded: A narrow viewport with a sensible clip height uses less memory than a full, very tall page. Large images, canvases, and PDFs can still consume substantial memory.
  • Record status: Save the URL, viewport, user agent, open status, render path, and timing for each job. This makes intermittent failures diagnosable.
  • Expect engine differences: Results can vary from current Safari or Chromium because PhantomJS is suspended and uses an older rendering engine.
  • Budget your own infrastructure: A local PhantomJS workflow has the cost of the machine, maintenance, retries, and storage. The cited PhantomJS documentation does not publish a performance benchmark.

Or skip the browser setup

ScreenshotNeo provides a hosted screenshot API when you need a repeatable capture without maintaining PhantomJS. It accepts one GET request and returns PNG, JPEG, WebP, or PDF. Cookie and consent banners, newsletter popups, and chat widgets are removed before the shot. Bot checks, blank pages, timeouts, failed loads, and cache hits are not billed, and response headers identify the page verdict and whether it was billed. An MCP server provides take_screenshot, get_page_info, and capture_pdf tools for Claude, Cursor, and other MCP clients.

See the ScreenshotNeo API documentation for all options. A basic request is:

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,
)
r.raise_for_status()
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 includes full-page capture with lazy images loaded, CSS-selector element capture, dark mode, device presets and custom viewports, retina scale, custom CSS and JavaScript, clicks, selector or network-idle waits, request blocking, headers, cookies, user agents, authorization, timezone, geolocation, transparent backgrounds, resizing, caching with a chosen TTL, signed links, asynchronous jobs with signed webhooks, bulk capture for up to 100 URLs per call, a usage API, and an OpenAPI specification. Existing parameter names used by other screenshot APIs also work.

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

FAQ

Does PhantomJS create a true iPhone screenshot?

No. It creates a screenshot at the viewport dimensions you specify. A user-agent string may alter server responses, but the documented features do not establish complete iPhone hardware or Safari emulation.

Should I set viewportSize or clipRect first?

Set both before navigation when you want predictable results. The viewport controls layout; the clip rectangle controls the captured bounds.

Why is the screenshot blank even though the URL opens?

Rendering may happen before client-side content appears, or the page may depend on browser APIs PhantomJS does not support. Add a bounded readiness wait and inspect resource and JavaScript errors.

Can PhantomJS capture a full-page mobile screenshot?

It can render a taller clipping rectangle, but you may need to trigger lazy loading and wait for images. Very tall captures increase memory use.

When should I replace PhantomJS?

Replace it when modern sites require APIs or rendering behavior unavailable in QtWebKit, when you need current browser fidelity, or when maintaining the legacy runtime costs more than using a hosted or current-browser capture system.