Skip to content

Commit 142c55e

Browse files
crisbetommalerba
authored andcommitted
fix(a11y): avoid errors when trying to add high contrast class (#18323)
Found this in some errors logs. The `document.defaultView` can be null in some cases which causes a null pointer error to be thrown. Furthermore, these changes add a few more null checks to ensure that we don't throw if `getComputedStyle` isn't available.
1 parent 09f2872 commit 142c55e

File tree

1 file changed

+6
-3
lines changed

1 file changed

+6
-3
lines changed

src/cdk/a11y/high-contrast-mode/high-contrast-mode-detector.ts

Lines changed: 6 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -62,10 +62,13 @@ export class HighContrastModeDetector {
6262

6363
// Get the computed style for the background color, collapsing spaces to normalize between
6464
// browsers. Once we get this color, we no longer need the test element. Access the `window`
65-
// via the document so we can fake it in tests.
66-
const documentWindow = this._document.defaultView!;
65+
// via the document so we can fake it in tests. Note that we have extra null checks, because
66+
// this logic will likely run during app bootstrap and throwing can break the entire app.
67+
const documentWindow = this._document.defaultView || window;
68+
const computedStyle = (documentWindow && documentWindow.getComputedStyle) ?
69+
documentWindow.getComputedStyle(testElement) : null;
6770
const computedColor =
68-
(documentWindow.getComputedStyle(testElement).backgroundColor || '').replace(/ /g, '');
71+
(computedStyle && computedStyle.backgroundColor || '').replace(/ /g, '');
6972
this._document.body.removeChild(testElement);
7073

7174
switch (computedColor) {

0 commit comments

Comments
 (0)