目錄表

Insert Google Analytics Script when HTTP Response

Requirement

Code

# jal.20140421: this aFleX collects the HTTP response and insert google analytics script before </head>
when HTTP_REQUEST {
  # remove "Accept-Encoding" header to make sure server doesn't send compressed response
  # (this is done automatically in Rel 2.6.1 and later)
  if { [HTTP::header exists "Accept-Encoding"] } {
    HTTP::header remove "Accept-Encoding"
  }
}
 
when HTTP_RESPONSE {
  # check Response Code and Content-Type to avoid unnecessary collects
  if { [HTTP::status] equals "200" && [HTTP::header "Content-Type"] contains "text/html" } {
    HTTP::collect
  }
}
 
when HTTP_RESPONSE_DATA {
  set clen [HTTP::payload length]
  regsub -all "</head>" [HTTP::payload] "
    <script language='javascript'>
      (function(i,s,o,g,r,a,m){i\['GoogleAnalyticsObject'\]=r\;i\[r\]=i\[r\]||function(){
      (i\[r\].q=i\[r\].q||\[\]).push(arguments)},i\[r\].l=1*new Date()\;a=s.createElement(o),
      m=s.getElementsByTagName(o)\[0\]\;a.async=1\;a.src=g;m.parentNode.insertBefore(a,m)
      })(window,document,'script','//www.google-analytics.com/analytics.js','ga')\;
 
      ga('create', 'UA-XXXXXXXX-Y', 'jal.tw')\;
      ga('require', 'displayfeatures')\;
      ga('require', 'linkid', 'linkid.js')\;
      ga('send', 'pageview')\;
    </script>
    </head>
  " newdata
  # Replace response data from 0 to old data length with new data.
  HTTP::payload replace 0 $clen $newdata
  HTTP::release
}