Skip to content

[Bug]: Firefox focus emulation stops at the top-level document #42933

Closed

Description

Version

1.62.1 (Firefox build 1538, Firefox 153.0)

Steps to reproduce

Two pages in two contexts of one Firefox instance. Page A focuses a button and counts blur events on its window; page B receives a single page.mouse.click().

// blur-repro.mjs — npm i [email protected] && npx playwright install && node blur-repro.mjs
import { chromium, firefox, webkit } from "playwright"

const INNER = `<button id="b">x</button>
<script>
  window.__blurs = 0
  window.addEventListener("blur", () => { window.__blurs++ })
</script>`

async function probe(browser, mode) {
  const a = await (await browser.newContext()).newPage()
  const b = await (await browser.newContext()).newPage()
  if (mode === "iframe") {
    await a.setContent('<iframe id="f"></iframe>')
    await a.evaluate((inner) => { document.getElementById("f").srcdoc = inner }, INNER)
    await a.waitForFunction(() => !!document.getElementById("f").contentDocument?.getElementById("b"))
  } else {
    await a.setContent(INNER)
  }
  const frame = mode === "iframe" ? a.frames().find((f) => f !== a.mainFrame()) : a.mainFrame()
  await frame.locator("#b").click()
  await frame.evaluate(() => { window.__blurs = 0 })
  await b.setContent("<p>other page</p>")
  await b.mouse.click(10, 10)
  await a.waitForTimeout(200)
  return frame.evaluate(() => ({ blurs: window.__blurs, hasFocus: document.hasFocus(), active: document.activeElement?.id }))
}

for (const [name, type] of Object.entries({ chromium, firefox, webkit })) {
  const browser = await type.launch({ headless: true })
  for (const mode of ["iframe", "top-level"]) {
    console.log(name, browser.version(), mode, await probe(browser, mode))
  }
  await browser.close()
}

Expected behavior

Firefox behaves like Chromium and WebKit: a page keeps its focused state regardless of input dispatched to other pages, and that holds for documents in child frames as much as for the top-level document. No blur on A's window, document.hasFocus() stays true.

Actual behavior

engine button lives in blur events on A after the click on B document.hasFocus() in A afterwards
chromium 151.0.7922.34 iframe 0 true
chromium 151.0.7922.34 top level 0 true
firefox 153.0 iframe 1 false
firefox 153.0 top level 0 true
webkit 26.5 iframe 0 true
webkit 26.5 top level 0 true

Linux arm64 (mcr.microsoft.com/playwright:v1.62.1-noble, Node 24.18.1, headless). macOS arm64 (Darwin 24.5, Node 22.17.1, Chrome channel 153.0.8010.53 instead of the bundled Chromium) gives identical Firefox rows: iframe 1 blur / hasFocus() false, top level 0 / true.

Only the top-level document is protected. A focused element inside an iframe still receives the window-level blur whenever another page of the same browser gets mouse input, and document.hasFocus() flips to false there.

Additional context

Why it happens (reading the patch, links point at main e5d880b):

  • juggler/protocol/TargetRegistry.js activateAndRun calls this._window.focus() before every Page.dispatchMouseEvent. In headless mode HeadlessWidget::RaiseWindow deactivates the previously active window, so Firefox runs its normal window-lowered path for page A.
  • The emulation that is supposed to absorb this is per docshell: nsFocusManager::BlurImpl skips the blur "when leaving document" only if the focused window's docshell has mOverrideHasFocus (bootstrap.diff#L824), and Document::HasFocus returns true only when mDocumentContainer->ShouldOverrideHasFocus() (#L719).
  • nsDocShell::ShouldOverrideHasFocus() returns the docshell's own flag (#L398-L400), while every other per-page override in the same patch resolves through the root docshell (IsBypassCSPEnabled, IsFileInputInterceptionEnabled, geolocation, reduced motion, forced colors, contrast — all return GetRootDocShell()->m…).
  • juggler/content/main.js#L52-L54 sets docShell.overrideHasFocus = true "for all top level documents" only. Child docshells never get it.

Chromium (Emulation.setFocusEmulationEnabled) and WebKit (Emulation.setActiveAndFocused) emulate per page without touching OS-level window activation, which is why they are unaffected.

A one-line fix, verified against a repacked build 1538:

--- a/browser_patches/firefox/juggler/content/FrameTree.js
+++ b/browser_patches/firefox/juggler/content/FrameTree.js
@@ -124,6 +124,7 @@ class FrameTree {
   _onDOMWindowCreated(window) {
     const frame = this.frameForDocShell(window.docShell);
     if (!frame)
       return;
+    window.docShell.overrideHasFocus = true;
     frame._onGlobalObjectCleared();
   }

content-document-global-created fires for every document in the page's frame tree, the frame is already registered by then (browsing-context-attached precedes the global), Fission is disabled in playwright.cfg so the child docshell lives in the same process, and the attribute is the same one main.js sets for the top-level docshell. For the top-level document the assignment is a no-op.

Verification, both with Playwright 1.62.1 and Firefox build 1538, juggler replaced inside omni.ja:

check stock 1538 patched 1538
repro above, Firefox, button in iframe — macOS arm64 1 blur, hasFocus() false 0 blurs, hasFocus() true
repro above, Firefox, button in iframe — Linux arm64 (v1.62.1-noble image) 1 blur, hasFocus() false 0 blurs, hasFocus() true
repro above, Firefox, button at top level (both platforms) 0 / true 0 / true
Vitest browser-mode suite (188 tests, every test in an iframe), 7 parallel Firefox pages, Linux arm64 fails every run: Radix Select test, locator.click: Timeout 5000ms exceeded ("element was detached from the DOM") 188/188, 3 of 3 runs
same suite, 12 parallel Firefox pages, macOS arm64 same failure 188/188

Alternative in C++, consistent with the neighbouring overrides: resolve ShouldOverrideHasFocus() through the root docshell (return GetRootDocShell()->mOverrideHasFocus;). GetRootDocShell() is non-const, so the method loses its const in the declaration (#L600) and definition — three changed lines, hunk sizes unchanged. Not built or tested on my side; the juggler change above is the one with the numbers behind it.

I understand browser_patches/ is rolled from playwright-browsers, so I am not opening a PR against the mirror. Happy to test a build or provide anything else that helps.

Impact: test runners that execute tests inside an iframe and drive several pages in parallel hit this constantly. Vitest browser mode opens maxWorkers pages per browser and renders every test in an iframe, so any component that closes on window blur (Radix Select, Popover, DropdownMenu, …) closes at random whenever another worker clicks. That is the Firefox-only flakiness behind vitest-dev/vitest#7916 (per-instance fileParallelism was added there as the workaround; fileParallelism: false for the Firefox instance is what we run today).

Environment

System:
    OS: macOS 15.5
    CPU: (14) arm64 Apple M3 Max
    Memory: 68.38 MB / 36.00 GB
  Binaries:
    Node: 22.17.1 - /Users/paulwille/.nvm/versions/node/v22.17.1/bin/node
    npm: 10.9.2 - /Users/paulwille/.nvm/versions/node/v22.17.1/bin/npm
    pnpm: 11.13.1 - /Users/paulwille/.nvm/versions/node/v22.17.1/bin/pnpm
  Languages:
    Bash: 3.2.57 - /bin/bash
  npmPackages:
    playwright: ^1.62.1 => 1.62.1

Activity

  1. github-actions commented on Sep 25, 2026

    @github-actions
    Contributor

    Hi, I'm the Playwright bot. I tried to reproduce this on macOS.

    Reproduced on tip-of-tree (npm [email protected], Firefox 156.0) on macOS (GitHub Actions macos-latest). I ran your script unchanged. In Firefox, a button focused inside an iframe gets one window blur, and document.hasFocus() becomes false once another context's page receives page.mouse.click(). A focused button in the top-level document is not affected. Chromium and WebKit are unaffected in both cases, so this only happens in Firefox. Headed and headless give the same result.

    Your reading of the source also checks out on main (afa6836):

    • juggler/content/main.js sets docShell.overrideHasFocus = true only on the top-level docshell.
    • nsDocShell::ShouldOverrideHasFocus() returns the docshell's own mOverrideHasFocus, while the neighbouring overrides go through GetRootDocShell().

    That means child-frame docshells never get the override. This looks like a real bug in Firefox focus emulation.

    Condensed repro (not run in the repo test suite)
    test('focus emulation should cover child frames', {
      annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/42933' },
    }, async ({ browser }) => {
      const a = await (await browser.newContext()).newPage();
      const b = await (await browser.newContext()).newPage();
      await a.setContent(`<iframe srcdoc='<button id="b">x</button><script>window.__blurs = 0; addEventListener("blur", () => window.__blurs++)</script>'></iframe>`);
      const frame = a.frames()[1];
      await frame.locator('#b').click();
      await b.setContent('<p>other page</p>');
      await b.mouse.click(10, 10);
      await a.waitForTimeout(200);
      expect(await frame.evaluate(() => ({ blurs: (window as any).__blurs, hasFocus: document.hasFocus() })))
          .toEqual({ blurs: 0, hasFocus: true }); // firefox: { blurs: 1, hasFocus: false }
    });
    What I ran
    • OS: macOS (GitHub Actions macos-latest), Node from the runner
    • version: tip-of-tree, npm [email protected] (chromium 155.0.8059.12, firefox 156.0, webkit 26.6)
    • script: the blur-repro.mjs from the issue, run headless and headed
    engine button in blurs hasFocus()
    chromium iframe 0 true
    chromium top level 0 true
    firefox iframe 1 false
    firefox top level 0 true
    webkit iframe 0 true
    webkit top level 0 true

    Headed and headless results are identical. I didn't re-test 1.62.1 because tip-of-tree still reproduces it. I also didn't build Firefox with either of your proposed fixes.

    Triaged on macOS by the Playwright bot - agent run

  2. added
    browser-firefox
    on Sep 25, 2026
  3. alok-108 commented on Sep 26, 2026

    @alok-108
    Contributor

    I have reproduced the issue locally on tip-of-tree and confirmed the root cause: focus emulation is applied in \juggler/content/main.js\ only to the top-level docshell (\docShell.overrideHasFocus = true), while child frames in \FrameTree.js\ do not receive this override (and in C++,
    sDocShell::ShouldOverrideHasFocus()\ checks only the local docshell rather than \GetRootDocShell()).

    Since the fix lives in \�rowser_patches/firefox/\ (\juggler/content/FrameTree.js\ or \�ootstrap.diff) rather than the \playwright-core\ client protocol layer, should we submit a PR updating \�rowser_patches/firefox/juggler/content/FrameTree.js, or will browser patch updates and the subsequent Firefox browser roll be handled by the core team?

  4. top-sigrid commented on Sep 29, 2026

    @top-sigrid
    Author

    Yury Semikhatsky (@yury-s) Thank you very much for fixing this so quickly 🙏🏼

  5. removed
    browser-firefox
    on Oct 27, 2026
  6. github-actions commented on Oct 28, 2026

    @github-actions
  7. github-actions commented on Oct 28, 2026

    @github-actions
    Contributor

    Hi, I'm the Playwright bot and I checked this again on Linux.

    Reproduced on current main (57decd26b623ab0291a4839ff976bbc94165ba32, Playwright 1.65.0-next, Firefox 158.0/r1569). A focused iframe receives a window blur and document.hasFocus() becomes false after another context's page receives mouse input. Chromium and WebKit pass, both headed and headless.

    The original fix was later reverted because it broke moving focus from an iframe to its parent (#43280). #43456 disabled this issue's Firefox regression test; it did not fix this issue. The current Firefox patches again apply the focus override only to the top-level docshell. This remains a bug in our Firefox focus-emulation patches, so I prepared a report for the browser team.

    Reproduction and results

    I extended the existing EM-023 test in tests/library/emulation-focus.spec.ts, removing its Firefox fixme, checking initial focus, and waiting 200 ms after the other page's click so queued blur events are included:

    browserTest('iframe focus survives another page receiving input', {
      annotation: { type: 'issue', description: 'https://github.com/microsoft/playwright/issues/42933' },
    }, async ({ contextFactory }) => {
      const page1 = await (await contextFactory()).newPage();
      const page2 = await (await contextFactory()).newPage();
      const srcdoc = `<button id=foo>foo</button><script>window.addEventListener('blur', () => window.gotBlur = true)</script>`;
      await page1.setContent(`<iframe srcdoc="${srcdoc}"></iframe><iframe srcdoc="${srcdoc}"></iframe>`);
      const [, frame1, frame2] = page1.frames();
      await frame1.click('#foo');
      expect(await frame1.evaluate(() => document.hasFocus())).toBe(true);
      await page2.setContent('<p>other page</p>');
      await page2.mouse.click(10, 10);
      await page1.waitForTimeout(200);
      expect({
        blurred: await frame1.evaluate(() => !!window['gotBlur']),
        focused: await frame1.evaluate(() => document.hasFocus()),
        siblingFocused: await frame2.evaluate(() => document.hasFocus()),
      }).toEqual({ blurred: false, focused: true, siblingFocused: false });
    });

    Ubuntu 24.04.5, x86_64; headed runs used Xvfb:

    Browser Mode Iframe result Top-level blur test
    Chromium 157.0.8103.15/r1252 Headless and headed Pass Pass
    Firefox 158.0/r1569 Headless and headed blurred: true, focused: false, siblingFocused: false Pass
    WebKit 27.2/r2380 Headless and headed Pass Pass

    Commands:

    npm run test -- tests/library/emulation-focus.spec.ts --grep 'EM-02[23]' --workers=1 --retries=0 --reporter=line
    xvfb-run -a npm run test -- tests/library/emulation-focus.spec.ts --grep 'EM-02[23]' --headed --workers=1 --retries=0 --reporter=line
    npm run ftest -- tests/page/page-focus.spec.ts --grep 'FO-01[12]' --workers=1 --retries=0 --reporter=line
    xvfb-run -a npm run ftest -- tests/page/page-focus.spec.ts --grep 'FO-01[12]' --headed --workers=1 --retries=0 --reporter=line

    Each six-test cross-browser run had five passes and the Firefox iframe failure. Both Firefox iframe-to-parent tests passed in both modes. An initial run without the 200 ms wait already observed hasFocus() === false, but had not yet observed the queued blur event. No historical npm releases or custom browser builds were tested in this pass.

    Blocked-by: https://github.com/microsoft/playwright-browsers/issues/2643

    Triaged on Linux by the Playwright bot - agent run

  8. added
    browser-firefox
    and removed on Oct 29, 2026
  9. pavelfeldman commented on Nov 2, 2026

    @pavelfeldman
    Member

    Should be fixed with the next browser roll.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    browser-firefox

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions