railslove / rack-tracker

Tracking made easy: Don’t fool around with adding tracking and analytics partials to your app and concentrate on the things that matter.
https://www.railslove.com/open-source
MIT License
647 stars 121 forks source link

Use leftmost match for gtm tag injection #156

Closed yutoji closed 4 years ago

yutoji commented 4 years ago

Issue

If the response html has no new line after <head> tag, the gtm script tag will be placed on a bad place.

Example1

In case response html is

<html><head></head><body></body></html>

Then the response after GoogleTagManager#inject is being:

<html><head></head><body><noscript><iframe src="https://www.googletagmanager.com/ns.html?id=somebody"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
</body></html>
  <script>
  (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
  new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
  j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
  'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
  })(window,document,'script','dataLayer','somebody');</script>

Example2

In case response html is

<html><head><script>console.log("hello");
console.log("world");
</script>
</head>
<body></body>
</html>

Then the response after GoogleTagManager#inject is being:

<html><head><script>
  <script>
  (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
  new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
  j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
  'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
  })(window,document,'script','dataLayer','somebody');</script>

console.log("hello");
console.log("world");</script>
</head>
<body><noscript><iframe src="https://www.googletagmanager.com/ns.html?id=somebody"
height="0" width="0" style="display:none;visibility:hidden"></iframe></noscript>
</body>
</html>

Solution

Use leftmost match for injection.

DonSchado commented 4 years ago

cool, thanks a lot!