Capture Mobile Browser Screenshots with PhantomJS
In this article
Capturing mobile browser screenshots with PhantomJS involves using a headless WebKit engine to emulate a mobile device's viewport dimensions and user agent string. By configuring the browser's width, height, and identity, you can render a webpage as it would appear on a smartphone and save that render as a PNG or JPEG file. This process is essential for automated visual regression testing, monitoring mobile site layouts across different screen resolutions, and generating previews for mobile-first designs without needing a physical device farm.
What You'll Need
- PhantomJS Binary: The executable installed on your system (Windows, macOS, or Linux).
- Terminal or Command Prompt: Access to a CLI to run the PhantomJS scripts.
- A Text Editor: VS Code, Sublime Text, or Notepad++ to write the JavaScript configuration files.
- Basic JavaScript Knowledge: Understanding of asynchronous functions and object properties.
- Target URL: The web address of the mobile site you wish to capture.
Step-by-Step
- Install PhantomJS: Download the appropriate binary for your operating system from the official archive. Ensure the binary is added to your system's PATH environment variable so you can call
phantomjsfrom any directory in your terminal. Verify the installation by runningphantomjs --version. - Create a Script File: Open your text editor and create a new file named
mobile_screenshot.js. PhantomJS operates by executing JavaScript files that instruct the headless browser on what to do. - Define Page Settings: Start your script by creating a new page object. You must specify the viewport size to match a mobile device. For example, for a standard iPhone-style view, set the width to 375 pixels and the height to 667 pixels. Use
page.setViewportSize(375, 667);. - Emulate the Mobile User Agent: Websites use the User-Agent string to determine whether to serve a desktop or mobile version of a page. To trigger the mobile layout, you must override the default PhantomJS agent. Set
page.settings.userAgent = "Mozilla/5.0 (iPhone; CPU iPhone OS 13_2_3 like Mac OS X) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.3 Mobile/15E148 Safari/604.1";. - Handle Page Loading: Use the
page.open()` method to navigate to your URL. Because web pages load assets asynchronously, you cannot take the screenshot immediately after the open command. You must use a callback function that triggers once theonloadevent fires. - Implement a Render Delay: Many mobile sites use JavaScript to render elements or load animations. To ensure the screenshot captures the fully rendered state, wrap the
clipContentmethod in asetTimeoutfunction. A delay of 2 to 5 seconds is usually sufficient for most mobile pages. - Capture the Screenshot: Use the
page.render('screenshot.png')method. If you want to capture the entire length of the mobile page (the full scroll) rather than just the viewport, you must first calculate the total height of the body element usingdocument.body.scrollHeightand update the viewport height dynamically before rendering. - Execute the Script: Save your file and run it from the terminal using the command
phantomjs mobile_screenshot.js. The resulting image file will be generated in the same directory as the script.
Common Mistakes
One of the most frequent errors is forgetting to set the User-Agent. If you only change the viewport size, the server will still see a desktop browser request and serve the desktop version of the site, which will look broken or zoomed-out when squeezed into a 375px width. Always pair viewport changes with a mobile User-Agent string.
Another common mistake is failing to account for asynchronous content. Modern mobile sites rely heavily on AJAX and lazy-loading images. If you capture the screenshot the millisecond the onload event triggers, you will often end up with a blank screen or a loading spinner. Implementing a manual wait time is the most reliable way to ensure all elements are visible.
Developers also frequently mistake the viewport height for the page height. Setting a viewport of 667px only captures the "above the fold" content. To capture a full-page mobile screenshot, you must execute a script within the page context to find the actual height of the document and resize the PhantomJS window to that exact height before calling the render function.
Tips
To capture multiple device profiles, create a JSON configuration file containing different widths, heights, and user agents for various devices (e.g., Android, iPad, iPhone). You can then loop through this JSON object in your JavaScript file to generate a suite of screenshots automatically.
For sites with complex CSS transitions, try disabling animations via the script. You can inject a CSS snippet into the page that sets * { transition: none !important; animation: none !important; }. This prevents the screenshot from capturing a half-finished fade-in effect.
If you are dealing with HTTPS sites that have expired or self-signed certificates, PhantomJS may block the connection. You can bypass this by setting page.settings.ignoreClientCertErrors = true; in your configuration to ensure the page loads regardless of certificate validity.
Troubleshooting
Blank Screenshots: If your output is a white or transparent image, the most likely cause is that the page has not finished loading. Increase your setTimeout value. Additionally, check if the site has a "bot detection" system that blocks headless browsers. If it does, you may need to refine your User-Agent string to look more authentic.
Incorrect Layout: If the page looks like a desktop site shrunk down, verify that your User-Agent string is correctly assigned and that there are no typos in the string. Ensure the setViewportSize method is called before the page.open method; changing the size after the page has started loading can sometimes lead to inconsistent rendering results.
Memory Leaks or Crashes: When capturing dozens of screenshots in a loop, PhantomJS can consume significant RAM. To prevent crashes, ensure you are properly closing page objects or restarting the PhantomJS process between large batches of screenshots.
Images Not Loading: Some mobile sites use lazy-loading, where images only load as the user scrolls. To fix this, you can write a small JavaScript snippet to be executed within the page that programmatically scrolls to the bottom of the page and back up again before the screenshot is taken.
Frequently Asked Questions
Can PhantomJS handle modern CSS Grid and Flexbox?
PhantomJS uses an older version of WebKit. While it supports basic Flexbox, it struggles with many modern CSS Grid properties and newer CSS specifications. For sites using cutting-edge CSS, the render may not be 100% accurate compared to a modern Chrome or Safari browser.
How do I capture the full length of a mobile page?
You must use page.evaluate to get the document.body.scrollHeight. Once you have this value, call page.setViewportSize(width, scrollHeight) before calling page.render().
Is PhantomJS still the best tool for this?
PhantomJS is excellent for lightweight, legacy tasks, but it is no longer actively developed. For projects requiring the latest web standards (like ES6+ or advanced CSS), tools like Puppeteer or Playwright are generally recommended as they control actual Headless Chrome or Firefox instances.
Can I capture screenshots of pages behind a login?
Yes, but you must first script the login process. You can use page.evaluate to fill in the username and password fields and click the submit button. Once the session cookie is set, you can navigate to the protected page and take the screenshot.
Does PhantomJS support WebP images?
Generally, no. Because it uses an older WebKit engine, it may not render WebP images correctly, which can result in missing images in your screenshots if the server only provides WebP formats.