Forum Discussion

avp4's avatar
Icon for Nimbostratus rankNimbostratus
Dec 14, 2022

Google Tag Manager

I've been asked to implement Google Tag Manager via an iRule. I have the Google code but am unsure how to implement. Does anyone have experience with this and can point me in the right direction? Thi...
  • JRahm's avatar
    Dec 16, 2022

    Seems you would just need 2 substitutions instead of one, like:

        set search1 "<head>"
        set search2 "<body>"
        set tracking_id [class match -value -- $host equals HOST_TRACKING_MAPPING]
        if { $tracking_id eq "" } {
            set tracking_id $static::default_trackingid
        HTTP::payload replace 0 $content_length [string map [list $search1 "<head>[subst -nocommands -nobackslashes [ifile get gtm_head.js]]" $search2 "<body>[subst -nocommands -nobackslashes [ifile get gtm_body.js]]"] [HTTP::payload]]

    Note: I'm just interpreting literally the notes here: If there's a reason it should not be at the top of head for performance or other reasons, find the slot you want it to sit and then make the line in head above that as your first search term.

    Just working in the tlcsh with substitute values, this works out like this:

    % set http_payload "<html><head><title>Hi there</title></head><body><p>This is a sentence</p></body></html>"
    <html><head><title>Hi there</title></head><body><p>This is a sentence</p></body></html>
    % set search1 <head>
    % set search2 <body>
    % set insert1 "<script>GTM_head_script_here</script>"
    % set insert2 "<script>GTM_body_script_here</script>"
    % string map [list $search1 "<head>[subst -nocommands -nobackslashes $insert1]" $search2 "<body>[subst -nocommands -nobackslashes $insert2]"] $http_payload
    <html><head><script>GTM_head_script_here</script><title>Hi there</title></head><body><script>GTM_body_script_here</script><p>This is a sentence</p></body></html>