Skip to content

The posthog-js library is throwing error, when user is iddle #2533

Closed

Description

@lukasbicus

Bug description

Our Sentry reported over 170 errors during the last month, with this error thrown:

SecurityError: Failed to read a named property 'removeEventListener' from 'Window': Blocked a frame with origin "https://app.tradespace.io" from accessing a cross-origin frame.
    at h (../../../node_modules/.pnpm/@rrweb+record@2.0.0-alpha.17_patch_hash=4a974d451d029e3ef6c302f641dfaf41fb0881146b6d5198ccdbe8d50776b64f/node_modules/@rrweb/record/dist/record.js:3615:1)
    at forEach (../../../node_modules/.pnpm/@rrweb+record@2.0.0-alpha.17_patch_hash=4a974d451d029e3ef6c302f641dfaf41fb0881146b6d5198ccdbe8d50776b64f/node_modules/@rrweb/record/dist/record.js:5571:27)
    at Array.forEach (<anonymous>)
    at call (../../../node_modules/.pnpm/@rrweb+record@2.0.0-alpha.17_patch_hash=4a974d451d029e3ef6c302f641dfaf41fb0881146b6d5198ccdbe8d50776b64f/node_modules/@rrweb/record/dist/record.js:5571:14)
    at LazyLoadedSessionRecording.stop (../src/extensions/replay/external/lazy-loaded-session-recorder.ts:791:9)
    at this._onSessionIdleResetForcedListener (../src/extensions/replay/external/lazy-loaded-session-recorder.ts:704:22)
    at SimpleEventEmitter.emit (../../../node_modules/posthog-js/src/utils/simple-event-emitter.ts:21:13)
    at this._enforceIdleTimeout (../../../node_modules/posthog-js/src/sessionid.ts:329:36)
    at sentryWrapped (../../../node_modules/@sentry/browser/src/helpers.ts:117:17)

Please describe.

How to reproduce

  1. The users were idle for a long period of time

Related sub-libraries

  • All of them
  • posthog-js (web)
  • posthog-js-lite (web lite)
  • posthog-node
  • posthog-react-native
  • @posthog/react
  • @posthog/ai
  • @posthog/nextjs-config

Additional context

The bug seems to happen to me, originating in the @rrweb/record@2.0.0-alpha.17 / using the @rrweb/record@2.0.0-alpha.17 in Posthog.

Updating to @rrweb/record@2.0.0-alpha.18 may help.

Any advice, how can this be fixed in our repository?

Activity

  1. lukasbicus commented on Oct 31, 2025

    @lukasbicus
    Author

    I noticed, we still use PostHogProvider from posthog-js/react. Is this package deprecated? Should we use @posthog/react?

  2. marandaneto commented on Nov 1, 2025

    @marandaneto
    Member

    @PostHog/team-replay probably a replay issue since i see 'rrweb' logs

  3. pauldambra commented on Nov 3, 2025

    @pauldambra
    Member

    hey @lukasbicus can you share a little more about how you're using posthog replay - since there's an iframe cross origin issue here... this is our tidy-up code running, i guess there's an assumption about the context it's running in that isn't true for your setup

    I noticed, we still use PostHogProvider from posthog-js/react. Is this package deprecated? Should we use @posthog/react?

    i don't think that will help here, but yep you should move over at some point - although posthog-js/react is just a passthrough to @posthog/react so it won't change anything except tidiness

  4. lukasbicus commented on Nov 3, 2025

    @lukasbicus
    Author

    Hi @pauldambra - thanks for taking a look.

    Here is what I found when I investigated the setup on our project:

    // We init PostHog like this:
    posthog.init(process.env.POST_HOG_API_KEY, {
      api_host: process.env.POST_HOG_HOST,
      defaults: '2025-05-24',
      disable_session_recording: currentUser?.tradespaceEmployee ? true : false,
      session_recording: {
        recordCrossOriginIframes: false
      }
    });
    
    if (currentUser) {
      posthog.identify(currentUser.uuid, {
        email: currentUser.email,
        name: currentUser.fullName,
        account_id: currentAccount.id,
        account_user_id: currentAccountUser.id
      });
    }
    import posthog from 'posthog-js';
    // We wrap the app in the PostHogProvider:
    // ...
      <PostHogProvider client={posthog}>
        {
          //... the app itself.
        }
      </PostHogProvider>

    We also use some feature flags on our project (useFeatureFlagEnabled from posthog-js/react).

    Is this helpful? I'm not quite sure, how to answer this question. I watch videos of users' behavior only on Sentry.

  5. pauldambra commented on Nov 3, 2025

    @pauldambra
    Member

    Does your application run in an iframe?

    When a user is idle for a long time and posthog recording is running we shut down the recorder to save resources and the error message looks like for some reason we can create the event listeners but when we are tearing down we get an error removing them 🫠

  6. lukasbicus commented on Nov 3, 2025

    @lukasbicus
    Author

    No, our application doesn't run in an iframe.

  7. pauldambra commented on Nov 3, 2025

    @pauldambra
    Member

    Hmmm, surprising the error has Blocked a frame with origin "https://app.tradespace.io/" from accessing a cross-origin frame.

    something is in a frame 🙈

  8. lukasbicus commented on Nov 3, 2025

    @lukasbicus
    Author

    Hmmm, surprising the error has Blocked a frame with origin "https://app.tradespace.io/" from accessing a cross-origin frame.

    something is in a frame 🙈

    Ouu, that can be a clue. Our app runs on https://app.tradespacestaging.io/ or https://app.tradespace.io/. Usually, people use it from the browser. If it is used in an iframe, it has to be a very specific kind of usage. I'll discuss with my team and let you know with further findings.

  9. pauldambra commented on Nov 3, 2025

    @pauldambra
    Member

    awesome, thank you!
    very happy to ship a fix here but don't know what it would be 🙈 😅

  10. lukasbicus commented on Nov 5, 2025

    @lukasbicus
    Author

    Hi @pauldambra - We get your point. Of course, this package can't resolve our CORS issues.

    Right now, we don't understand where the root of the issue is, as we don't use our app in an iframe 99 percent of the time, and the error happens on pages distant from this iframe. We will watch this issue further. Thanks for your insights.

  11. pauldambra commented on Nov 5, 2025

    @pauldambra
    Member

    No worries, thanks for you patience with the back-and-forth here

    Do let us know how it goes, since even if it's not something we could fix (and ofc it might still be) we might be able to output a nicer error that makes this easier for the future traveller!

  12. filipgymdesk commented on Nov 11, 2025

    @filipgymdesk

    I was also able to reproduce this one on my local, by just idling for a longer period of time ~30 mins on the screen where the posthog is called. No iframe here as well

    record.js:3615 Uncaught SecurityError: Failed to read a named property 'removeEventListener' from 'Window': Blocked a frame with origin "https://localhost.test" from accessing a cross-origin frame.
    at Ie.stop (lazy-loaded-session-recorder.ts:876:9)
    at lazy-loaded-session-recorder.ts:753:22
    at Cn.emit (simple-event-emitter.ts:21:13)
    at sessionid.ts:330:36

    using the php sdk, probably after reply inactivity it tries to do a cleanup?

    Seems to fail on
    this._stopRrweb?.()

  13. 14 remaining items

  14. xKelvin commented on Mar 9, 2026

    @xKelvin

    @pauldambra
    Hey Paul, sorry completely missed your response.

    I can give you a link to the error inside of error tracking within our PostHog environment if you're interested.
    Though I am unable to reproduce the error myself reliably, for now here is at least part of the stack trace which I can see there:

    DOMException: SecurityError: Failed to read a named property 'removeEventListener' from 'Window': An attempt was made to break through the security policy of the user agent.
    File "turbopack:///[project]/node_modules/.pnpm/posthog-js@1.357.1/node_modules/posthog-js/src/sessionid.ts", line: 333, in: this._enforceIdleTimeout
    this._eventEmitter.emit('forcedIdleReset', { idleSessionId })
    File "turbopack:///[project]/node_modules/.pnpm/posthog-js@1.357.1/node_modules/posthog-js/src/utils/simple-event-emitter.ts", line: 20, in: SimpleEventEmitter.emit
    listener(payload)
    File "../src/extensions/replay/external/lazy-loaded-session-recorder.ts", line: 944, in: LazyLoadedSessionRecording.stop
    window?.removeEventListener('offline', this._onOffline)
    File "../src/extensions/replay/external/sessionrecording-utils.ts", line: 79, in: event
    const event = _event as pluginEvent<{ payload: string[] }>
    File "../src/extensions/replay/external/lazy-loaded-session-recorder.ts", line: 1038, in: LazyLoadedSessionRecording.onRRwebEmit
    const throttledEvent = this._mutationThrottler ? this._mutationThrottler.throttleMutations(rawEvent) : rawEvent
    File "../../../node_modules/.pnpm/@posthog+rrweb-record@0.0.45/node_modules/@posthog/rrweb-record/dist/rrweb-record.js", line: 18204, in: <anonymous>
    File "Unknown Source", in: Array.forEach
    File "../../../node_modules/.pnpm/@posthog+rrweb-record@0.0.45/node_modules/@posthog/rrweb-record/dist/rrweb-record.js", line: 18204, in: <anonymous>
    File "../../../node_modules/.pnpm/@posthog+rrweb-record@0.0.45/node_modules/@posthog/rrweb-record/dist/rrweb-
    

    Exception properties, from one of the occurrences:

    Prop value
    Synthetic false
    Library web 1.357.1
    Handled false
    Browser Chrome 145
    OS Mac OS X 10.15.7

    Also I used the Claude Code PostHog plugin to create a report which may be of use!
    Beware of the dates as this issue has been happening for a while, and well before the 'first seen' as listed below.

    Details (data from last 7 days)

    Error Data Summary for PostHog Team

    Issue Overview

    Field Value
    Status Active
    First seen 2026-03-07 05:30:11 UTC
    Last seen 2026-03-08 07:17:09 UTC
    Occurrences 2
    Unique sessions 2
    Unique users 2
    posthog-js version 1.357.1
    rrweb package @posthog/rrweb-record@0.0.45

    Both Occurrences

    Occurrence 1 (2026-03-07 05:30:11 UTC):

    • OS: Windows 10, Chrome 145, Desktop
    • Viewport: 1280x665
    • Page: Authenticated content page
    • Session entry: Direct (no referrer)
    • Recording status: active

    Occurrence 2 (2026-03-08 07:17:09 UTC):

    • OS: Mac OS X 10.15.7, Chrome 145, Desktop
    • Viewport: 1307x709
    • Page: Authenticated content page
    • Recording status: active

    Stack Trace (identical for both)

    @posthog/rrweb-record@0.0.45/dist/rrweb-record.js:13582  ← SecurityError thrown here
      ↑ Array.forEach
      ↑ @posthog/rrweb-record@0.0.45/dist/rrweb-record.js:18204
      ↑ LazyLoadedSessionRecording.onRRwebEmit (lazy-loaded-session-recorder.ts:1038)
      ↑ event / stop (sessionrecording-utils.ts:79)
      ↑ LazyLoadedSessionRecording.stop (lazy-loaded-session-recorder.ts:944)
      ↑ SimpleEventEmitter.emit (simple-event-emitter.ts:20)
      ↑ this._enforceIdleTimeout (sessionid.ts:333)   ← TRIGGER
    

    Our PostHog Init Config

    posthog.init(key, {
      api_host: 'https://<our-domain>/event',  // proxied via Next.js rewrite
      ui_host: 'https://eu.posthog.com',
      defaults: '2025-05-24',
      capture_pageview: false,
      capture_pageleave: true,
      rageclick: false,
      autocapture: { element_allowlist: ['a', 'button', 'select'] },
      capture_exceptions: true,
      debug: false,  // (true in dev only)
    });
    // No disable_session_recording
    // No recordCrossOriginIframes
    // configured_session_timeout_ms: 1800000 (default 30 min)

    Key Environment Facts

    • Framework: Next.js 16 (App Router) with Turbopack
    • No iframes in our own code — grep for <iframe across all .ts/.tsx files returns zero results
    • CSP is set with: frame-src 'self' https://challenges.cloudflare.com https://js.stripe.com https://www.facebook.com
    • The only possible iframes would come from Cloudflare Turnstile CAPTCHA (login/register pages) or Stripe checkout — but neither affected page loads those
    • Both affected pages are standard server-rendered Next.js pages — no third-party embeds, no PDF viewers, no iframes
    • Chrome 145 on both occurrences — could be browser-specific
    • Error message says "An attempt was made to break through the security policy of the user agent" (not the cross-origin frame variant) — this wording suggests the browser's built-in security policy is blocking the access, not a CSP header

    Reproduction Note

    We cannot reliably reproduce this. It happens intermittently when users idle on the page and the 30-min session timeout fires _enforceIdleTimeout. Both occurrences were on pages with no iframes whatsoever in the DOM.

    Hypothesis

    rrweb may be holding stale references to windows/frames from earlier in the session (e.g., from a Cloudflare Turnstile CAPTCHA on login) and failing to clean them up when those frames no longer exist or have been navigated away from. The teardown at rrweb-record.js:13582 then throws when iterating those stale references.

  15. jperezrealini commented on Mar 16, 2026

    @jperezrealini

    Same as @xKelvin here 🙋‍♂️

  16. erezcor commented on Mar 18, 2026

    @erezcor

    This looks like it was fixed upstream in rrweb-io/rrweb#1695, which shipped in @rrweb/record's 2.0.0-alpha.19 release.

    The fix simply wraps the handlers.forEach teardown in a try-catch that silently ignores cross-origin errors.

    From what I see, PostHog JS currently uses 2.0.0-alpha.17 with a custom patch - if that's the root cause, the fix would need to be either cherry-picked into the patch or the dependency upgraded to alpha.19 or alpha.20.

    @pauldambra @marandaneto

  17. pauldambra commented on Mar 18, 2026

    @pauldambra
    Member

    oh intriguing.

    yep, we diverged at alpha17 because alphas 18 introduced performance problems during recording.

  18. kyleswank commented on Mar 24, 2026

    @kyleswank
    Contributor

    I've got a user encountering this (or something very similar) in this ticket.

    This is likely relevant:

    The iframes in question are likely third-party embeds (payment forms, OAuth popups, etc.) that load same-origin initially then redirect

    So we add a listener, or the iframe is accessible temporarily, then upon redirect becomes inaccessible and when tear down happens it causes the error. Not sure if that gives you anything new @pauldambra that you didn't already know!

    I also see this error still happening with 1.363.4 which I believe the above PR was in.

  19. colonal commented on Mar 29, 2026

    @colonal

    I'm experiencing the same issue.

    SecurityError: Failed to read a named property 'removeEventListener' from 'Window': An attempt was made to break through the security policy of the user agent.

    This is causing significant noise in Sentry — we've seen around 70K events triggered by this error alone. It doesn't seem to impact end users directly, but it creates a lot of noise in monitoring.

    From what I can tell, this might already be addressed in rrweb alpha.18. Also, there seems to be a related fix in posthog-rrweb:
    PostHog/posthog-rrweb#145

    However, I'm not entirely sure how posthog-js is currently tied to posthog-rrweb, or whether these fixes are already included or planned to be included.

    Are there any plans to upgrade to a newer rrweb version (e.g. alpha.18 or later) in the near future?

    Currently using:
    "posthog-js": "^1.352.1"

  20. pauldambra commented on Apr 2, 2026

    @pauldambra
    Member

    since 1.363.6 we're now not reacting to any error that matches error instanceof DOMException && error.name === 'SecurityError' in this teardown

    would appreciate confirmation (or not) that folk are no longer seeing this

  21. pauldambra commented on Apr 2, 2026

    @pauldambra
    Member
  22. colonal commented on Apr 2, 2026

    @colonal

    Thanks for the update!

    I'm still seeing this issue on version 1.364.1. It's also visible in the PostHog Inspector.

    I've attached a screenshot for reference.

    Let me know if you need any additional information or if there's anything I can help test.

    Image
  23. pauldambra commented on Apr 2, 2026

    @pauldambra
    Member

    ok, that's super useful. i think
    we also need PostHog/posthog-rrweb#163

  24. pauldambra commented on Apr 2, 2026

    @pauldambra
    Member

    ok, i'm out for 4 days now and I don't want to lumber someone else with watching my release so i'll merge this next week

    #3328

    you can safely ignore this error in your error tracking tool of choice if you don't want to wait till next week

  25. marandaneto commented on Apr 29, 2026

    @marandaneto
    Member

    fixed in current rrweb package updates

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

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions