Skip to content

Use leftmost match for gtm tag injection#156

Merged
DonSchado merged 1 commit intorailslove:masterfrom
yutoji:fix-google-tag-manager-one-line-html-bug
Jul 17, 2020
Merged

Use leftmost match for gtm tag injection#156
DonSchado merged 1 commit intorailslove:masterfrom
yutoji:fix-google-tag-manager-one-line-html-bug

Conversation

@yutoji
Copy link
Copy Markdown
Contributor

@yutoji yutoji commented Jul 8, 2020

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.

If the response html has no new line after <head> tag,
the gtm script tag will be placed on a invalid place.
@yutoji yutoji changed the title Use leftmost match in gtm tag injection Use leftmost match for gtm tag injection Jul 9, 2020
@DonSchado DonSchado merged commit 0a09c94 into railslove:master Jul 17, 2020
@DonSchado
Copy link
Copy Markdown
Collaborator

cool, thanks a lot!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants