From efcf96aba1e4d264468113ff423225dc2593d507 Mon Sep 17 00:00:00 2001 From: crisbeto Date: Wed, 29 Jan 2020 09:55:09 +0100 Subject: [PATCH] fix(a11y): avoid errors when trying to add high contrast class 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. --- .../high-contrast-mode/high-contrast-mode-detector.ts | 9 ++++++--- 1 file changed, 6 insertions(+), 3 deletions(-) diff --git a/src/cdk/a11y/high-contrast-mode/high-contrast-mode-detector.ts b/src/cdk/a11y/high-contrast-mode/high-contrast-mode-detector.ts index b1a78cf58d6f..41600e0219d1 100644 --- a/src/cdk/a11y/high-contrast-mode/high-contrast-mode-detector.ts +++ b/src/cdk/a11y/high-contrast-mode/high-contrast-mode-detector.ts @@ -62,10 +62,13 @@ export class HighContrastModeDetector { // Get the computed style for the background color, collapsing spaces to normalize between // browsers. Once we get this color, we no longer need the test element. Access the `window` - // via the document so we can fake it in tests. - const documentWindow = this._document.defaultView!; + // via the document so we can fake it in tests. Note that we have extra null checks, because + // this logic will likely run during app bootstrap and throwing can break the entire app. + const documentWindow = this._document.defaultView || window; + const computedStyle = (documentWindow && documentWindow.getComputedStyle) ? + documentWindow.getComputedStyle(testElement) : null; const computedColor = - (documentWindow.getComputedStyle(testElement).backgroundColor || '').replace(/ /g, ''); + (computedStyle && computedStyle.backgroundColor || '').replace(/ /g, ''); this._document.body.removeChild(testElement); switch (computedColor) {