Florian Gössele
Florian Gössele

Reputation: 4678

How to prevent Google Tag Manager overwriting document.write()?

We are using Angular for our Website. As not all Pages have been ported to Angular, we implemented a hybrid approach:

  1. Every request goes to Angular first. When it has been loaded, it checks if the Route exists
  2. If not, the HTML-page is fetched from the backend
  3. The html-Element in the DOM (i.e. the complete page) is replaced with the response's body
ngOnInit() {
  this.railsService.fetchRailsPage(this.router.url).subscribe(
    (response) => this.replaceDOM(response),
    (errorResponse) => this.replaceDOM(errorResponse.error)
  );
}

private replaceDOM(newContent: string) {
  document.open();
  document.write(newContent);
  document.close();
}

Since all a-hrefs in old pages are plain old hrefs (not Angular's routerLinks), once the user navigates away, the page is reloaded and Angular kicks in again.

So far, it works, but: I noticed that sometimes the DOM is not replaced with the response body.

Debugging brought us to the conclusion that Google Tag Manager could be the issue. It overwrites document.write() and a lot of other default Javascript functions.

enter image description here

Why is that? And how can this be prevented to get the default version of e.g. document.write()?

Upvotes: 1

Views: 611

Answers (1)

BNazaruk
BNazaruk

Reputation: 8111

Seconding Alan here.

Please make sure you're running two tests:

  1. Block gtm with the request blocking function of the dev tools and try reproducing the issue.

  2. Try creating an empty GTM container, loading it on page and reproduce the issue.

If the first test shows that The issue persists with GTM blocked, then it's not GTM.

If the second test shows that the issue is solved, then it's not about GTM but about the logic used in it's configuration.

If anything, I would first make sure no custom code in GTM additionaly overrides document.write (which I've never seen before, but it's definitely possible). Then I would broadly audit all custom scripts deployed by GTM. After that, I would try pausing all the element visibility triggers if any are deployed and seeing if that helps.

GTM likely would aim to override write to be able to watch DOM changes. But it does so gently, adding a bit of tracking there and not changing the essence of it. It's severely unlikely that GTM's core logic would conflict with Angular.

//UPD just had a chat with a colleague on Measure. It looks like the only scenario when GTM overrides the document.write is when there are Custom HTML tags that have an option to "support document.write". The Element Visibility trigger uses mutation and intersection observers rather than listening to document.writes.

Upvotes: 1

Related Questions