Skip to content

getDocumentHeight never reports a smaller value, iframe auto-resize only grows and never shrinks #8886

Description

@dylanmoz

🐛 bug report

Preflight Checklist

  • I have read the Contributing Guidelines for this project.
  • I agree to follow the Code of Conduct that this project
    adheres to.
  • I have searched the issue tracker for an issue that matches the one I want
    to file, without success.

Description of the problem

getDocumentHeight() in packages/app/src/sandbox/compile.ts includes html.offsetHeight in its Math.max:

function getDocumentHeight() {
  const { body } = document;
  const html = document.documentElement;
  return Math.max(body.scrollHeight, body.offsetHeight, html.offsetHeight);
}

Since <html> fills the iframe, html.offsetHeight always equals the iframe's current height. Once the iframe grows (e.g. to 1098px), getDocumentHeight() can never return a smaller value — the measurement is self-referencing. This means the { type: 'resize', height } message dispatched to the parent will never report a decrease in content height.

How has this issue affected you? What are you trying to accomplish?

We embed Sandpack previews in a chat UI where the iframe should match content height exactly (no scrollbar). When the user resizes their browser to a narrower width, the content reflows and becomes shorter, but the iframe stays at its previous (taller) height, leaving empty space below the content.

To Reproduce

  1. Embed a <SandpackPreview> with no fixed height (relying on auto-resize)
  2. Let the content render — iframe grows to match content (e.g. 1098px)
  3. Resize the browser window to a smaller width
  4. Content reflows responsively and becomes shorter (e.g. 600px)
  5. Expected: iframe shrinks to ~600px
  6. Actual: iframe stays at 1098px — sendResize polling detects no change because getDocumentHeight() still returns 1098

Suggested fix

Exclude html.offsetHeight from the measurement, or temporarily set html.style.height = '0' / 'auto' before measuring:

function getDocumentHeight() {
  const { body } = document;
  return Math.max(body.scrollHeight, body.offsetHeight);
}
Software Name/Version
Сodesandbox Bundler https://2-19-8-sandpack.codesandbox.io/
Browser Chrome 148.0.7778.168
Operating System macOS

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions