Search code examples
javascriptiisurl-rewriting

How do I embed javascript into an IIS UrlRewrite rule?


Context: Azure, Windows Server 2012 R2, IIS 8

The standard rewrite providers in IIS 8 are { and '}' and these are used in various contexts to represent captures, replacements and symbols, e.g. {C:0}, {R:1}, {HTTP_ORIGIN}.

I'm trying to use a rule to inject Google Tag Manager markup into a page.

<rule name="Inject GTM After HEAD" preCondition="ResponseIsHtml1" enabled="true">
  <match filterByTags="None" pattern="&lt;head.*?>" />
  <conditions logicalGrouping="MatchAll" trackAllCaptures="true" />
  <action type="Rewrite" value="{R:0}&lt;!-- Google Tag Manager --> &lt;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'?'&amp;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','GTM-XXXX');&lt;/script> &lt;!-- End Google Tag Manager -->" />
</rule>

This does NOT work as the JavaScript contains { and IIS's UrlRewrite tool immediately complains with a yellow box reading The rewrite provider " w[l]=w[l]||[];w[l].push( { 'gtm.start'" does not exist (note that it terminates at the : which would separate the usual R or C from the numeric qualifier.)

I have tried swapping { with &#123; but this doesn't work well, giving me the following in the generated web page:

<!DOCTYPE HTML>
<html lang="en">
    <head><!-- Google Tag Manager --> <script>(function(w,d,s,l,i) &#123; w[l]=w[l]||[];w[l].push( &#123; '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','GTM-XXXX');</script> <!-- End Google Tag Manager -->
    <meta charset="UTF-8"/>

Naturally the browser complains about dodgy JavaScript code.

IIS has been around for a long time. I expect the solution is obvious to someone. What is the usual thing to do to make inclusion of JavaScript possible?

LATER

It has been suggested that I google with the word "inject". Cool idea. Results?

  1. Microsoft demonstrates how to insert a JavaScript comment.
  2. Webtuna demonstrates how to inject a reference to an online resource, but not a slab of JavaScript code. This would work fine if it wasn't for the fact that I'm trying to embed a GTM block.
  3. EG Innovations has lots of good info but again the code sample provided doesn't contain braces.

Solution

  • I have documented the procedure I used at DEV.

    Essentially, we put the GTM code in a js file on a different subdomain and embed a script tag with a src pointing at that js file.