mzuccaroli / angular-google-tag-manager

A service library for integrate google tag manager in your angular project
https://itnext.io/how-to-add-google-tag-manager-to-an-angular-application-fc68624386e2
MIT License
138 stars 78 forks source link

document is not defined on SSR #159

Closed ciekals11 closed 11 months ago

ciekals11 commented 1 year ago

TL;DR Injecting GoogleTagManagerService into component that is preloaded with ssr results in ReferenceError: document is not defined

I'm using SSR with my angular application and I'm facing an issue with angular-google-tag-manager example code:

export class AppComponent implements OnInit {
    constructor(
        protected gtmService: GoogleTagManagerService,
        @Inject(PLATFORM_ID) private platformId: Object
    ) {}

    ngOnInit(): void {
        if (!isPlatformBrowser(this.platformId)) {
            void this.gtmService.addGtmToDom();
        }
    }
}

This results in:

ReferenceError: document is not defined at Object.documentRef (/dist/<project_name>/server/main.js:232935:9)

After inspecting this file i have found faulty peace of code:

this.browserGlobals = {
    windowRef() {
        return window;
    },

    documentRef() {
        return document; // <------- this generates mentioned error
    }

};

In constructor of GoogleTagManagerService