title: Tracking banner impressions and clicks on external website with javascript
body: <p>I am serving some banners to external 3rd party websites and need to track impressions and clicks per website and also need to modify the banner images and links from time to time without requesting the 3rd parties to do this on their websites</p>
  
  <p>I have come up with the following that tracks the clicks using GA campaigns and tracks the impressions as requests in IIS logs on my server.</p>
  
  <p>HTML to include on external 3rd party websites</p>
  
  <pre><code>&lt;div id="affBanner" style="width:500px"&gt;&lt;/div&gt;
  &lt;script src="http://www.mywebsite.com/affiliates.js"&gt;&lt;/script&gt;
  </code></pre>
  
  <p>Contents of affiliates.js</p>
  
  <pre><code>var affHost = window.location.hostname.replace(/[^0-9a-zA-Z]/g, "");
  var affBanner = document.getElementById('affBanner');
  affBanner.innerHTML = '&lt;a href="http://mywebsite.com?utm_source='+affHost+'"  target="_blank"&gt;&lt;img src="http://mywebsite.com/images/banner.jpg?aff='+affHost+'" alt="" style="width:100%;" /&gt;&lt;/a&gt;';
  </code></pre>
  
  <p>This is working but I have 2 questions.</p>
  
  <ol>
  <li><p>I am gathering input in the form of the hostname and then sanitizing it with a regex before using it in the banner link href and the image source. Is this code vulnerable XSS or other attack?</p></li>
  <li><p>Does anyone have any suggestions how this code could be improved or another method of achieving a similar result? Please keep in mind I am trying to make this as simple as possible.</p></li>
  </ol>