Commit efa0d4f
authored
fix(cdk/scrolling): handle null document.body in ViewportRuler (#32477)
We've been encountering runtime errors in our production monitoring system:
`TypeError: Cannot read properties of null (reading 'scrollTop')`
The error originates from `ViewportRuler.getViewportScrollPosition` when
accessing `document.body.scrollTop` and `document.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.body` can be `null`
when 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.ts` incorrectly types `document.body` as
non-nullable `HTMLElement`, which masks this issue at compile time but
allows the runtime error to occur.
Related TypeScript issues:
- microsoft/TypeScript#50078 (documentElement nullability)
- microsoft/TypeScript#22868 (body type issue)
Added optional chaining (`?.`) when accessing `document.body.scrollTop`
and `document.body.scrollLeft` to 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.1 parent c62c64f commit efa0d4f
1 file changed
Lines changed: 5 additions & 2 deletions
| Original file line number | Diff line number | Diff line change | |
|---|---|---|---|
| |||
125 | 125 | | |
126 | 126 | | |
127 | 127 | | |
128 | | - | |
| 128 | + | |
| 129 | + | |
| 130 | + | |
| 131 | + | |
129 | 132 | | |
130 | 133 | | |
131 | 134 | | |
132 | 135 | | |
133 | 136 | | |
134 | 137 | | |
135 | | - | |
| 138 | + | |
136 | 139 | | |
137 | 140 | | |
138 | 141 | | |
| |||
0 commit comments