fix(cdk/scrolling): handle null document.body in ViewportRuler #32477
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
We've been encountering runtime errors in our production monitoring system:
TypeError: Cannot read properties of null (reading 'scrollTop')The error originates from
ViewportRuler.getViewportScrollPositionwhen accessingdocument.body.scrollTopanddocument.body.scrollLeft.Creating a minimal reproduction is impractical, as the issue occurs during edge cases in page navigation/unload cycles in a large application.
According to the WHATWG HTML specification,
document.bodycan benullwhen the document element is not<html>or has no<body>/<frameset>child element. This typically occurs during page navigation or document unload when the DOM structure is being torn down.Spec: https://html.spec.whatwg.org/multipage/dom.html#dom-document-body
TypeScript's
lib.dom.d.tsincorrectly typesdocument.bodyas non-nullableHTMLElement, which masks this issue at compile time but allows the runtime error to occur.Related TypeScript issues:
document.documentElementcould benullactually microsoft/TypeScript#50078 (documentElement nullability)Added optional chaining (
?.) when accessingdocument.body.scrollTopanddocument.body.scrollLeftto safely handle the null case.Note: This PR focuses on fixing the immediate issue in
ViewportRuler. If accepted, similar patterns elsewhere in the codebase can be addressed in follow-up PRs.