Skip to content

Commit

Permalink
fix: safety check for window in common module. (#8816)
Browse files Browse the repository at this point in the history
* Currently if someone renders his Angular application using server side rendering, the `MatCommonModule` will throw an error due to missing `window` variable checks.

Fixes #8809
  • Loading branch information
devversion authored and mmalerba committed Dec 8, 2017
1 parent 3011236 commit a6cedd2
Show file tree
Hide file tree
Showing 2 changed files with 11 additions and 4 deletions.
11 changes: 9 additions & 2 deletions src/lib/core/common-behaviors/common-module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -37,6 +37,9 @@ export class MatCommonModule {
/** Reference to the global `document` object. */
private _document = typeof document === 'object' && document ? document : null;

/** Reference to the global 'window' object. */
private _window = typeof window === 'object' && window ? window : null;

constructor(@Optional() @Inject(MATERIAL_SANITY_CHECKS) private _sanityChecksEnabled: boolean) {
if (this._areChecksEnabled() && !this._hasDoneGlobalChecks) {
this._checkDoctypeIsDefined();
Expand All @@ -52,7 +55,7 @@ export class MatCommonModule {

/** Whether the code is running in tests. */
private _isTestEnv() {
return window['__karma__'] || window['jasmine'];
return this._window && (this._window['__karma__'] || this._window['jasmine']);
}

private _checkDoctypeIsDefined(): void {
Expand Down Expand Up @@ -90,7 +93,11 @@ export class MatCommonModule {

/** Checks whether HammerJS is available. */
_checkHammerIsAvailable(): void {
if (this._areChecksEnabled() && !this._hasCheckedHammer && !window['Hammer']) {
if (this._hasCheckedHammer || !this._window) {
return;
}

if (this._areChecksEnabled() && !this._window['Hammer']) {
console.warn(
'Could not find HammerJS. Certain Angular Material components may not work correctly.');
}
Expand Down
4 changes: 2 additions & 2 deletions src/universal-app/prerender.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
import {enableProdMode} from '@angular/core';
import {renderModuleFactory} from '@angular/platform-server';
import {readFileSync, writeFileSync} from 'fs-extra';
import {log} from 'gulp-util';
Expand All @@ -7,7 +6,8 @@ import 'reflect-metadata';
import 'zone.js';
import {KitchenSinkServerModuleNgFactory} from './kitchen-sink/kitchen-sink.ngfactory';

enableProdMode();
// Do not enable production mode, because otherwise the `MatCommonModule` won't execute
// the browser related checks that could cause NodeJS issues.

const result = renderModuleFactory(KitchenSinkServerModuleNgFactory, {
document: readFileSync(join(__dirname, 'index.html'), 'utf-8')
Expand Down

0 comments on commit a6cedd2

Please sign in to comment.