OneSignal / onesignal-ngx

OneSignal Angular
Other
5 stars 5 forks source link

window not defined with angular universal ssr (Server Side Rendering) #6

Closed kumarmanishc closed 2 years ago

kumarmanishc commented 2 years ago

I did integration of OneSignal with angular App.

This used to working fine with normal angular project.

After I added angular Universal it is giving error ReferenceError: window is not defined

This is the code where it stucks.

this.oneSignal.on('notificationDisplay', function (event) {
      console.log('New Notification:', event);
    });
FawadNL commented 2 years ago

We have the same issue when using Angular server side rendering @rgomezp

rgomezp commented 2 years ago

Howdy, This is a good question. Here are a couple of things you can try.

1. Create a shim for the window object (source)

npm install domino

In server.ts:

const domino = require('domino');
const fs = require('fs');
const path = require('path');

// Use the browser index.html as template for the mock window
const template = fs.readFileSync(path.join(__dirname, '.', 'dist', 'index.html')).toString();

// Shim for the global window and document objects.
const window = domino.createWindow(template);
global['window'] = window;

2. Use isPlatformBrowser (source)

import { PLATFORM_ID } from '@angular/core';
import { isPlatformBrowser, isPlatformServer } from '@angular/common';

constructor( @Inject(PLATFORM_ID) platformId: Object) {
  this.isBrowser = isPlatformBrowser(platformId);
}

Then use the isBrowser value to conditionally invoke OneSignal service code.

rgomezp commented 2 years ago

Closing due to inactivity