How to Access Iframe Elements With PhantomJS
Switch into an iframe with PhantomJS, query its document with page.evaluate(), handle nested frames, and avoid common serialization and timing errors.

To access an element inside an iframe with PhantomJS, switch the active page context to that frame, then run page.evaluate() to query the frame’s document. Return serializable data such as text, attributes, HTML, or a plain object. Call page.switchToMainFrame() when you need to work on the top-level document again.
PhantomJS’s frame APIs support selecting a frame by name or numeric position. The active frame determines which document a later evaluate() call sees.
1. Complete working example
var page = require('webpage').create();
page.open('https://example.com', function (status) {
if (status !== 'success') {
console.error('Unable to load the page');
phantom.exit(1);
return;
}
// Select by name when the iframe has a name attribute.
var switched = page.switchToFrame('checkout');
if (!switched) {
console.error('Frame not found');
phantom.exit(1);
return;
}
// This document is now the iframe's document.
var text = page.evaluate(function () {
var node = document.querySelector('.total');
return node ? node.textContent : null;
});
console.log(text);
// Restore the top-level document before doing parent-page work.
page.switchToMainFrame();
phantom.exit();
});
Replace checkout and .total with the frame name and selector used by your page. The selector in this example is illustrative; inspect the target page when the frame is unnamed or generated dynamically.
2. Find the correct iframe
Use a frame name
If the markup includes name="payment", select it directly:

if (!page.switchToFrame('payment')) {
throw new Error('payment frame was not found');
}
Use a numeric frame position
When no stable name exists, inspect the child frames of the current context:
console.log('count:', page.framesCount);
console.log('names:', JSON.stringify(page.framesName));
var position = 0; // choose after inspecting framesName and the page structure
if (!page.switchToFrame(position)) {
console.error('No frame at position ' + position);
phantom.exit(1);
return;
}
Frame positions are relative to the currently active frame. A position that works in the main document may refer to a different child after you switch into a nested frame.
Inspect iframe elements in the parent document
window.frames[index] is a child frame’s Window object, equivalent to the iframe element’s contentWindow; it is not the DOM <iframe> element. Query the parent document when you need the element’s attributes:
page.switchToMainFrame();
var iframeInfo = page.evaluate(function () {
var frame = document.querySelector('iframe');
if (!frame) return null;
return {
src: frame.getAttribute('src'),
name: frame.getAttribute('name'),
id: frame.id,
title: frame.getAttribute('title')
};
});
console.log(JSON.stringify(iframeInfo));
3. Query content after switching
Every page.evaluate() function runs in the active browsing context. Switch first, then query:
page.switchToFrame('profile');
var profile = page.evaluate(function () {
var name = document.querySelector('.user-name');
var link = document.querySelector('a.profile-link');
return {
name: name ? name.textContent.trim() : null,
href: link ? link.getAttribute('href') : null,
html: document.body ? document.body.innerHTML : null
};
});
console.log(JSON.stringify(profile));
page.switchToMainFrame();
The evaluate bridge accepts JSON-serializable arguments and return values. DOM nodes, functions, and closures cannot be returned as live PhantomJS objects.
4. Nested iframes
For nested frames, enter each level in sequence. At each level, inspect framesCount and framesName again because they describe children of the current frame.
page.switchToMainFrame();
if (!page.switchToFrame('outer-frame')) {
throw new Error('Outer frame not found');
}
console.log('inner names:', JSON.stringify(page.framesName));
if (!page.switchToFrame('inner-frame')) {
throw new Error('Inner frame not found');
}
var value = page.evaluate(function () {
var el = document.querySelector('[data-result]');
return el ? el.getAttribute('data-result') : null;
});
console.log(value);
page.switchToParentFrame(); // one level up
page.switchToMainFrame(); // top-level document
Use switchToParentFrame() to move up one level, or switchToMainFrame() to reset the context completely.
5. Return data, not DOM handles
This fails conceptually because a DOM node cannot cross the evaluate boundary:
// Do not return the element itself.
var element = page.evaluate(function () {
return document.querySelector('.price');
});
Return the fields your script needs instead:
var element = page.evaluate(function () {
var node = document.querySelector('.price');
if (!node) return null;
return {
text: node.textContent.trim(),
html: node.outerHTML,
className: node.className,
value: node.getAttribute('data-value')
};
});
Supported practical return values include strings, numbers, booleans, null, arrays, and plain objects made from those values.
6. Wait for dynamic iframe content
An iframe can exist before its document has finished loading or before application code inserts the target element. Do not assume that a fixed delay works for every site. Use the page’s load and event behavior or poll for a site-specific condition, then switch and evaluate.

var system = require('system');
var page = require('webpage').create();
var deadline = Date.now() + 10000;
page.open('https://example.com', function (status) {
if (status !== 'success') {
console.error('Page load failed');
phantom.exit(1);
return;
}
function checkFrame() {
if (Date.now() > deadline) {
console.error('Timed out waiting for iframe content');
phantom.exit(1);
return;
}
if (!page.switchToFrame('checkout')) {
window.setTimeout(checkFrame, 100);
return;
}
var ready = page.evaluate(function () {
return !!document.querySelector('.total');
});
if (!ready) {
page.switchToParentFrame();
window.setTimeout(checkFrame, 100);
return;
}
var total = page.evaluate(function () {
var node = document.querySelector('.total');
return node ? node.textContent.trim() : null;
});
console.log(total);
phantom.exit();
}
checkFrame();
});
Keep the wait condition specific to the element or state you need. A frame name alone does not prove that its application content is ready.
7. Read the active frame’s HTML
page.frameContent exposes the content string for the currently active frame. It is useful for diagnostics or simple snapshots, but it is not a live DOM handle.
page.switchToFrame('content');
console.log(page.frameContent);
page.switchToMainFrame();
8. Troubleshooting
| Symptom | Cause | Fix |
|---|---|---|
querySelector() returns null |
The evaluation ran in the parent document, or the iframe content was not ready. | Switch to the intended frame first and wait for the target condition. |
switchToFrame() returns false |
The name or position does not identify a child of the current frame. | Print framesName and framesCount in the current context, then select again. |
| A returned element is empty or unusable | DOM nodes are not JSON-serializable across evaluate(). |
Return textContent, an attribute, outerHTML, or a plain object. |
| The wrong frame is selected by index | Frame order changed or the index was interpreted relative to another frame. | Prefer a stable frame name; otherwise enumerate children immediately before switching. |
| Nested content cannot be found | Only the outer frame was selected. | Enter each parent frame in order and inspect child names/counts at every level. |
| Parent selectors stop working | The active context is still a child frame. | Call switchToParentFrame() or switchToMainFrame(). |
| Content appears intermittently | Application code populates the iframe asynchronously. | Poll for a meaningful selector or state with a bounded timeout instead of relying on a universal delay. |
| The page fails before frame access | The top-level navigation did not succeed. | Check the status passed to page.open() and stop before frame operations when it is not success. |
9. Performance and reliability practices
- Use a frame name whenever the site provides a stable one; it avoids repeated discovery and is clearer than a magic index.
- Inspect frame names and counts only when needed, then query the smallest selector that proves readiness.
- Return only the fields required by your script. Large HTML strings increase serialization and memory work.
- Reset to the main frame after each operation so later code does not accidentally query a child document.
- Bound asynchronous waits. A missing frame or selector should produce a clear timeout rather than an endless polling loop.
- Expect frame structure and timing to depend on the page’s scripts. The API defines how selection works, not the contents or readiness of every website.
10. What PhantomJS can and cannot access
Frame switching changes the document context available to page scripts. It does not turn a frame into a normal parent-page element, and it does not bypass browser security boundaries. If a page’s frame is unavailable, changes after load, or depends on behavior PhantomJS cannot execute, the documented frame calls alone cannot guarantee access.
For a frame embedded in the same page, use the workflow above: identify the child, switch into it, query, serialize the result, and restore the previous context. If you need the iframe tag itself, stay in the parent document and query iframe directly.
Or skip the browser setup
If your end goal is a clean screenshot rather than DOM interaction, ScreenshotNeo provides a website screenshot API and MCP server. It handles the browser setup through one request and supports PNG, JPEG, WebP, and PDF output.
cURL:
curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp
Python:
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)
Node.js:
const q = new URLSearchParams({ access_key: 'YOUR_API_KEY', url: 'https://stripe.com' });
const res = await fetch(`https://api.screenshotneo.com/v1/shot?${q}`);
See the ScreenshotNeo documentation for request options. Cookie 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 billing result. Its MCP server includes take_screenshot, get_page_info, and capture_pdf for AI agents. The free plan includes 1,000 screenshots per month with no card; paid plans start at $5 for 3,000 shots.
Create a free ScreenshotNeo account with 1,000 screenshots a month and no card.
FAQ
Should I select an iframe by name or position?
Use a stable name when available. Use a position only after inspecting framesName and framesCount in the current context.
Can I return an iframe element from evaluate()?
No. Return serializable properties such as its source URL, title, attributes, text, or HTML.
How do I leave a child frame?
Call switchToParentFrame() for one level or switchToMainFrame() to return to the top-level page.
What does window.frames[0] represent?
It represents the child frame’s Window, not the parent document’s iframe DOM element.
Why does a frame exist but contain no target element?
The frame may still be loading or its application may populate content asynchronously. Wait for a page-specific selector or state with a timeout.


