Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

To switch Puppeteer to a window opened by the current page, capture that page from the opener’s popup event and call bringToFront() on it. Register the event listener before the click that opens the window:

const popupPromise = page.waitForEvent('popup');
const actionPromise = page.click('a.opens-popup');

const [popup] = await Promise.all([popupPromise, actionPromise]);
await popup.bringToFront();

bringToFront() activates the popup tab. It is different from page.focus(selector), which focuses a DOM element inside a page. The examples below include a version-compatible event-listener fallback, URL-based target discovery, loading checks, diagnostics and recovery for popups that fail to open.

What “focus” means in Puppeteer

Puppeteer has two operations that are often confused:

  • Tab or window activation: await popup.bringToFront() makes the popup the active page in the browser.
  • Element focus: await popup.focus('input[name="email"]') focuses a matching element in that page’s document. It rejects if no matching element exists.

The popup is still a Page in the opener’s BrowserContext; opening another browser window does not create a separate context. Puppeteer’s Page API recommends the opener’s popup event for identifying a page created by that opener. See the Page class documentation and BrowserContext documentation.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
#1 Best Overall
Sale
Philips 24 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 241V8LB
  • 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

Preferred method: wait for the opener’s popup event

Using the event-waiting helper

Start waiting before the action. This prevents a fast popup from opening and emitting its event before your code begins listening.

import puppeteer from 'puppeteer';

const browser = await puppeteer.launch({headless: true});
const page = await browser.newPage();

try {
  await page.goto('https://example.com', {waitUntil: 'domcontentloaded'});

  const popupPromise = page.waitForEvent('popup');
  const clickPromise = page.click('a.opens-popup');
  const [popup] = await Promise.all([popupPromise, clickPromise]);

  if (!popup) {
    throw new Error('The popup event did not provide a Page');
  }

  await popup.bringToFront();
  await popup.waitForNetworkIdle({idleTime: 500, timeout: 15000}).catch(() => {});
  console.log('Popup URL:', popup.url());
  console.log('Popup title:', await popup.title());
} finally {
  await browser.close();
}

The Promise.all pairing is important: the click triggers the event while the event wait is already pending. Adjust the selector and destination to your application. A popup event is documented as carrying Page | null, so retaining the null check is prudent.

When your installed version lacks waitForEvent

Event helper names can differ between Puppeteer releases. The underlying event is stable, so attach a one-time listener directly:

const popupPromise = new Promise(resolve => page.once('popup', resolve));
const clickPromise = page.click('a.opens-popup');
const [popup] = await Promise.all([popupPromise, clickPromise]);

if (!popup) throw new Error('No popup Page was emitted');
await popup.bringToFront();

Installations documented around Puppeteer 25.9.0 through 25.12.0 expose the APIs linked in this article, but verify event-waiting helpers against the version pinned in your project.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #2
Philips 22 Inch Computer Monitor FHD 100Hz VA VESA Flicker-Free, 221V8LB
  • 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

Complete workflow for a popup you need to use

1. Make the opener ready

await page.goto('https://app.example.test/login', {
  waitUntil: 'domcontentloaded',
  timeout: 30000
});
await page.waitForSelector('button.open-auth');

2. Capture and activate the popup

const popupPromise = new Promise(resolve => page.once('popup', resolve));
await Promise.all([
  popupPromise,
  page.click('button.open-auth')
]);
const popup = await popupPromise;

if (!popup) throw new Error('Popup was not created');
await popup.bringToFront();

In production code, use the single Promise.all assignment shown earlier rather than awaiting the same promise in separate statements. The example above is expanded only to show the sequence.

3. Wait for the popup’s own content

await popup.waitForSelector('form#auth', {visible: true, timeout: 15000});
await popup.focus('input[name="username"]');
await popup.type('input[name="username"]', process.env.USERNAME);
await popup.type('input[name="password"]', process.env.PASSWORD);
await popup.click('button[type="submit"]');

Use bringToFront() once for activation, then normal page methods such as waitForSelector, focus, type and click against the popup object.

Fallback: find a popup by target URL or another property

Use BrowserContext.waitForTarget() when the opener event is not suitable, such as an extension popup or a workflow where a unique URL identifies the desired page.

const context = page.browserContext();
const targetPromise = context.waitForTarget(
  target => target.url() === 'https://example.com/popup'
);

await page.click('a.opens-popup');
const target = await targetPromise;
const popup = await target.page();

if (popup) {
  await popup.bringToFront();
  await popup.waitForSelector('main');
}

Make the predicate specific. A broad match can select an already-open tab or an unrelated popup. You can also test target type, URL pathname or another property exposed by the target. Target.page() returns a Page for page-like targets and null for other target types. References: waitForTarget() and Target.page().

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #3
Sale
Dell 24 Monitor - SE2426H - 23.8-inch FHD (1920x1080) 144Hz 1ms Display, in-Plane Switching (IPS) Technology, AMD FreeSync™, TÜV 3-Star 2X HDMI, Tilt
  • 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.

Extension-popup example

For a Chrome extension, combine a type and URL predicate so an ordinary tab cannot satisfy the wait:

const targetPromise = context.waitForTarget(target =>
  target.type() === 'page' &&
  target.url() === 'chrome-extension://EXTENSION_ID/popup.html'
);
const target = await targetPromise;
const extensionPopup = await target.page();
if (!extensionPopup) throw new Error('Extension target is not a page');
await extensionPopup.bringToFront();

Puppeteer’s Chrome Extensions guide demonstrates the target-matching approach for extension popups.

Listing pages for diagnostics

Page lists help you inspect what exists, but they do not associate a newly created page with its opener as directly as the popup event.

const contextPages = await page.browserContext().pages();
console.log(contextPages.map(p => p.url()));

const allBrowserPages = await browser.pages();
console.log(allBrowserPages.map(p => p.url()));

BrowserContext.pages() lists pages in one context. Browser.pages() lists pages across contexts. Ordinary listings omit non-visible targets such as background pages; use target APIs when you need broader discovery. See BrowserContext.pages() and Browser.pages().

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Rank #4
Sale
Samsung 27" Essential S3 (S36GD) Series FHD 1800R Curved Computer Monitor
  • 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

Timeouts, blocked popups and reliable recovery

Give the wait a bounded timeout

A site may block popups, require a user gesture, or fail to load. Do not leave automation waiting forever. If your installed helper accepts a timeout option, set it; otherwise race the event promise with a timer:

function timeout(ms) {
  return new Promise((_, reject) =>
    setTimeout(() => reject(new Error(`Popup timeout after ${ms} ms`)), ms)
  );
}

const popupPromise = new Promise(resolve => page.once('popup', resolve));
await Promise.all([
  Promise.race([popupPromise, timeout(15000)]),
  page.click('a.opens-popup')
]);
const popup = await popupPromise;
if (!popup) throw new Error('Popup event returned null');
await popup.bringToFront();

For a production implementation, clear or replace the timer after the popup arrives so it cannot produce an unhandled rejection. A helper with a built-in timeout is preferable when available in your version.

Check whether the click can legally open a window

  • Perform the click as a direct consequence of the page action; some browsers block script-created windows without a user gesture.
  • Verify the selector points to the actual link or button, not an overlay or disabled clone.
  • Check that the site did not navigate the opener instead of creating a popup.
  • Inspect browser console and page errors, and log popup.url() immediately after capture.

Handle a popup that closes itself

OAuth and payment flows can close after redirecting. Attach close handling before interacting further:

popup.once('close', () => console.log('Popup closed'));
await popup.bringToFront();
if (popup.isClosed()) throw new Error('Popup closed before interaction');

Do not use obsolete target access for this job

Page.target() is marked obsolete in the API documentation, which directs users to the opener’s popup event for spawned pages. Use page.on('popup') or page.waitForEvent('popup') instead. See Page.target().

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.
Best Value
Sale
Sceptre New 22-Inch Gaming Monitor, FHD 1080p, Up to 144Hz, HDMI, DisplayPort, Built-in Speakers, Machine Black (E225W-FW144 Series, 2026)
  • 【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.
Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Choosing between the two discovery methods

Method Best fit Strength Main caution
Opener popup event A known page directly opens the desired window Directly associates the new page with its opener Must attach the listener before the triggering action
BrowserContext.waitForTarget() A unique URL, target type or property identifies the page Works for extension and other target-oriented workflows A weak predicate can match the wrong existing page
pages() enumeration Diagnostics and inventory Shows currently known pages Does not identify the newly spawned page reliably by itself

Performance and reliability practices

  • Register one short-lived popup listener for each action, rather than leaving permanent listeners that accumulate across tests.
  • Wait only for the readiness condition you need. domcontentloaded is usually faster than waiting for every asset; use a selector or a bounded network-idle wait for application readiness.
  • Reuse the existing BrowserContext when the popup needs the opener’s cookies or storage. Creating a separate context changes authentication state.
  • Close popup pages after each test to prevent resource leaks: if (!popup.isClosed()) await popup.close();.
  • Log the opener URL, popup URL, target type and timeout reason. These values distinguish selector failures from blocked windows and navigation errors.

Or skip the browser setup

If your goal is a static screenshot rather than interacting with a popup, ScreenshotNeo provides a single HTTP request. It accepts cookie and consent banners as a visitor and removes more than 60 known consent platforms, newsletter popups and chat widgets before capture; each cleanup step can be disabled. Bot checks or CAPTCHAs, blank pages, timeouts, failed loads and cache hits are not billed, and each response reports its result in X-Page-Verdict and X-Billed headers. Its MCP server supplies take_screenshot, get_page_info and capture_pdf tools to Claude, Cursor and other MCP clients.

Use the ScreenshotNeo documentation for all options. A direct cURL capture is:

curl -G "https://api.screenshotneo.com/v1/shot" -d access_key=YOUR_API_KEY --data-urlencode url=https://stripe.com -o shot.webp

The same request in 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)

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

ScreenshotNeo includes full-page and element capture, device and retina settings, PDF controls, custom CSS and JavaScript, click and wait actions, request blocking, headers, cookies, geolocation, transparent backgrounds, resizing, selectable cache TTLs, signed links, asynchronous webhooks, bulk capture for up to 100 URLs per call, a usage API and an OpenAPI specification. 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 screenshots. Create a free ScreenshotNeo account.

Frequently asked questions

Frequently Asked Questions

Does Puppeteer need a separate BrowserContext for a popup?

No. A window opened by a page remains in that opener’s BrowserContext, so it normally shares that context’s cookies and storage.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Why does my popup variable become null?

The documented popup event payload is Page or null. Check the value, add a bounded timeout, and verify that the click actually creates a page rather than navigating the opener.

Can I focus an input after switching to the popup?

Yes. First call popup.bringToFront(), then call popup.focus(selector) or another element method against the popup page.

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.