Set page.customHeaders and add cookies with page.addCookie() before calling page.open(). Check that the cookie was accepted and that navigation succeeded, then call page.render() from the successful load callback. By default, custom headers apply to requests for both the page and its resources.
Set headers and cookies before opening the page
This example follows the documented PhantomJS APIs. It is a practical sequence, not a claim that the code has been tested against a particular site. Replace the example values with credentials and headers appropriate to your target.
As an Amazon Associate I earn from qualifying purchases.
var page = require('webpage').create();
// Set the user agent through the dedicated setting.
page.settings.userAgent = 'ExampleUserAgent';
// By default, these headers apply to page and resource requests.
page.customHeaders = {
'X-Example': 'value',
'DNT': '1'
};
var cookieAdded = page.addCookie({
name: 'session',
value: 'example-value',
domain: 'example.com',
path: '/',
httponly: true,
secure: true
});
if (!cookieAdded) {
console.log('Cookie was not added; check its domain and attributes.');
phantom.exit(1);
}
page.open('https://example.com/', function (status) {
if (status !== 'success') {
console.log('Page did not load successfully: ' + status);
phantom.exit(1);
return;
}
page.render('screenshot.png');
phantom.exit();
});
The cookie domain must match the target page. A successful return from page.addCookie() means PhantomJS added it; it does not guarantee that the site will accept the session or that the server will authorize the request. Likewise, a successful page.open() callback is the point to render, but does not guarantee that the page’s content or authentication state is what you intended.
Quick wins for a faster PC:
Fix the driver behind crashes, sound loss and screen glitchesFind Drivers →Clear out junk files and repair common Windows errorsFree Scan →Scan for outdated or missing drivers - takes under a minuteDriver Scan →Choose the right scope for headers
Use page.customHeaders for shared request headers
Set page.customHeaders before page.open(). The property sends additional HTTP headers for every request issued by the page, including resource requests. Header names and values are encoded as US-ASCII. See the PhantomJS customHeaders documentation.
#1 Best Overall
- CRISP CLARITY: This 23.8″ Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
- WORK SEAMLESSLY: This sleek monitor is virtually bezel-free on three sides, so the screen looks even bigger for the viewer. This minimalistic design also allows for seamless multi-monitor setups that enhance your workflow and boost productivity
- A BETTER READING EXPERIENCE: For busy office workers, EasyRead mode provides a more paper-like experience for when viewing lengthy documents
Do not set User-Agent as an ordinary custom header when you want to configure the page’s user agent. Use page.settings.userAgent. The custom header can override the value configured through that setting, so avoid defining User-Agent in both places unless overriding it is deliberate.
Limit a header to the initial navigation
If the custom headers should accompany the initial navigation but not later page and resource requests, clear them in page.onInitialized. Set the handler before calling page.open():
Rank #2
- CRISP CLARITY: This 22 inch class (21.5″ viewable) Philips V line monitor delivers crisp Full HD 1920x1080 visuals. Enjoy movies, shows and videos with remarkable detail
- 100HZ FAST REFRESH RATE: 100Hz brings your favorite movies and video games to life. Stream, binge, and play effortlessly
- SMOOTH ACTION WITH ADAPTIVE-SYNC: Adaptive-Sync technology ensures fluid action sequences and rapid response time. Every frame will be rendered smoothly with crystal clarity and without stutter
- INCREDIBLE CONTRAST: The VA panel produces brighter whites and deeper blacks. You get true-to-life images and more gradients with 16.7 million colors
- THE PERFECT VIEW: The 178/178 degree extra wide viewing angle prevents the shifting of colors when viewed from an offset angle, so you always get consistent colors
page.customHeaders = { 'X-Example': 'value' };
page.onInitialized = function () {
page.customHeaders = {};
};
page.open('https://example.com/', function (status) {
if (status === 'success') {
page.render('screenshot.png');
}
phantom.exit();
});
This is the documented workaround for narrowing the header scope. If the target uses redirects or makes requests in an unexpected order, verify which requests actually carry the header in your maintained environment.
The Tool Desk
Outbyte PC Repair FREERepair Windows errors before they cause bigger problemsFix Now →Outbyte Driver Updater FREEScan for outdated or missing drivers - takes under a minuteDriver Scan →Use a request hook for per-resource handling
For request-level changes, PhantomJS provides page.onResourceRequested(requestData, networkRequest). The networkRequest object has a setHeader(key, value) method:
Rank #3
- Clear visuals. Fluid motion: A 144Hz refresh rate and 1ms MPRT deliver smooth, tear‑free motion across work, gaming, and streaming for clearer, more fluid viewing.
- Eye comfort: TÜV Rheinland 3‑star* certification reduces harmful blue light while preserving stunning color quality without compromise. *TÜV Rheinland 3-star eye comfort certification.
- Wide viewing angle: Get consistent views across a wide 178° /178° viewing angle.
- In-Plane Switching (IPS): See excellent color accuracy and consistency across wide viewing angles with In-plane Switching (IPS) technology.
- Ultra-thin bezels: Maximize your viewing experience with thin bezels.
page.onResourceRequested = function (requestData, networkRequest) {
// Add a header to this request when your own conditions match.
networkRequest.setHeader('X-Example', 'value');
};
Use the request metadata to decide which requests should be changed. The API documents the hook but does not establish every precedence rule or site-specific outcome. Check the resulting request flow rather than assuming a header is applied only where intended. See onResourceRequested.
Add and inspect cookies correctly
Add a cookie with page.addCookie()
Pass a cookie object before opening the URL. The documented fields include name, value, domain, and path; optional attributes include httponly, secure, and expires. The method returns whether the cookie was added successfully. A mismatched domain can cause it to be ignored or rejected. See the addCookie API.
Rank #4
- CURVED FOR ENHANCED ENGAGEMENT: An immersive viewing experience with a curved monitor that wraps more closely around your field of vision; It creates a wider view, enhancing depth perception and minimizing peripheral distraction
- SMOOTH PERFORMANCE FOR SEAMLESS CONTENT: Stay in the action when playing games, watching videos, or working on creative projects; The 100Hz refresh rate reduces lag and motion blur so you don't miss a thing in fast-paced moments¹
- MORE GAMING POWER: Gain the edge with optimizable game settings; Color and image contrast can be adjusted to see scenes more vividly and spot enemies hiding in the dark; Game Mode adjusts any game to fill the screen so you can view every detail²
- KEEP IT EASY ON THE EYES: Care for your eyes and stay comfortable, even during long sessions; Advanced eye comfort technology certified by TÜV reduces eye strain by minimizing blue light and reducing irritating screen flicker²
- INCREASED VERSATILITY: Connect to more; Plug devices straight into your monitor for increased flexibility, making your computing environment even more convenient
Set secure: true only when appropriate for the target’s HTTPS context. Supply an expiration only when the cookie needs one and you know the expected format and lifetime. The API call does not bypass server-side session rules, consent requirements, or other access controls.
Do these 3 things before closing this tab:
1Fix the driver behind crashes, sound loss and screen glitches2Repair Windows errors before they cause bigger problems3Scan for outdated or missing drivers - takes under a minuteUse page.cookies to inspect visible cookies
page.cookies exposes cookies visible to the current URL and may include cookies already in PhantomJS’s CookieJar. It is not the preferred way to create a cookie: PhantomJS recommends page.addCookie() when setting one. Consult the cookies property documentation.
Best Value
- 【INTEGRATED SPEAKERS】Whether you're at work or in the midst of an intense gaming session, our built-in speakers provide rich and seamless audio, all while keeping your desk clutter-free.
- 【EASY ON THE EYES】 Protect your eyes and enhance your comfort with Blue-Light Shift technology. This feature reduces harmful blue light emissions from your screen, helping to alleviate eye strain during long hours of use and promoting healthier viewing habits.
- 【WIDEN YOUR PERSPECTIVE】Our sleek minimal bezel design ensures undivided attention. The nearly bezel-free display seamlessly connects in a dual monitor arrangement, delivering an unobstructed view that lets you focus on more at once, completely distraction-free.
Render only after a successful load
Call page.render() from the page.open() callback after checking that the status is success. The automation guide documents rendering and the page.clipRect property for choosing the screen area to capture. For example, set a clip rectangle before opening the page if you want a bounded capture:
page.clipRect = { top: 0, left: 0, width: 1280, height: 800 };
Without a clip rectangle, the rendering behavior depends on the page and PhantomJS configuration. Confirm the dimensions and content of the output in your own script. The Page Automation with PhantomJS guide covers the webpage methods.
Troubleshooting
- The cookie is missing: Check the cookie’s domain against the URL’s host, and check the boolean result of
page.addCookie(). Confirm the cookie’s path and security attributes are suitable for the target. - The page loads but authentication fails: A cookie being added locally does not prove the server accepts it. Check that the cookie value is current and that the target actually uses that session cookie; inspect the cookies visible to the page and the server’s response.
- A header appears on images or scripts too: That is the default scope of
page.customHeaders. Clear the object inpage.onInitializedfor the documented initial-navigation workaround, or use the resource-request hook when per-request handling is needed. - The configured User-Agent is not used: Set
page.settings.userAgentand remove any conflicting User-Agent entry frompage.customHeaders, unless overriding it is intentional. - The screenshot is blank or incomplete: Render only after the successful load callback, then verify the loaded content and capture dimensions. A successful navigation callback does not prove the intended page content appeared.
- Behavior differs on a current site: The PhantomJS API and automation pages are legacy documentation. They do not establish compatibility with current websites, TLS behavior, or server policies. Validate the script in the specific PhantomJS environment you maintain.
Or skip the browser setup
If you need a screenshot endpoint instead of maintaining PhantomJS request setup, ScreenshotNeo accepts a URL in one GET request and returns an image or PDF. For example, save a WebP response with cURL:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://example.com/ -o shot.webp
See the ScreenshotNeo API documentation for request options. Cookie banners are accepted and removed, and 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, with response headers indicating the page verdict and billing status. An MCP server gives AI agents screenshot, page-information, and PDF-capture tools. The free plan includes 1,000 screenshots a month with no card; paid plans start at $5 for 3,000. Sign up for 1,000 free screenshots a month, with no card required.
Frequently Asked Questions
Does `page.customHeaders` apply to images and scripts as well as the document?
Yes. By default it applies to page and resource requests; use the documented `onInitialized` workaround or a request hook when you need narrower handling.
Can `page.addCookie()` guarantee that a site will log me in?
No. It only reports whether PhantomJS added the cookie. The domain must match, and the server still decides whether the cookie represents a valid session.
Quick Recap
Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.
Recommended Free Tools




