Cross-domain Google Analytics Campaign Transposing


/ Published in: JavaScript
Save to your folder(s)

This script was written to allow transposing of utm_campaign, utm_source and utm_medium query parameters from the URL of a landing page link to all of the links on that page that re-directed to the primary domain where users would actually convert. This is highly useful when sending out email campaigns that link people to a landing page on a hosted service such as Unbounce and your conversion points exist on a different top-level domain as it will allow you to see the campaign, medium and source values on the top-level domain Google Analytics conversion reports, even though the visitor initially landed on a different top-level domain.


Copy this code and paste it in your HTML
  1. /**
  2.  * URL link updater for cross-site UTM code transposing
  3.  *
  4.  * Update the validURLPattern variable regular expression to match your desired pattern
  5.  * that indicates link HREF values that go to the second-site.
  6.  */
  7. try {
  8. // URL pattern regular expression, change this to match your call to action links
  9. var validURLPattern = new RegExp("my-conversion-point-domain\.com");
  10. // The search string
  11. var queryStr = document.location.search;
  12.  
  13. // Only update if we have UTM parameters
  14. if(queryStr.match(/utm_campaign|utm_source|utm_medium/)){
  15. // Build object of UTM parameters
  16. var utm = {
  17. campaign: queryStr.match(/utm_campaign/) ? queryStr.match(/utm_campaign\=([^&]*)/)[1] : "",
  18. source: queryStr.match(/utm_source/) ? queryStr.match(/utm_source\=([^&]*)/)[1] : "",
  19. medium: queryStr.match(/utm_medium/) ? queryStr.match(/utm_medium\=([^&]*)/)[1] : ""
  20. };
  21.  
  22. // Loop through all A tags and update
  23. $('a').each(function(){
  24. // Only update if HREF matches the URL pattern
  25. if(this.href.match(validURLPattern)){
  26. // Determine starting separator
  27. var sep = this.href.indexOf("?") == -1 ? "?" : "&";
  28.  
  29. // Loop through UTM parameters to update
  30. for(var k in utm){
  31. // Check if URL already contains this UTM parameter
  32. if(this.href.indexOf("utm_" + k) != -1){
  33. var regexp = new RegExp("utm_" + k + "=([^&]*)");
  34. this.href = this.href.replace(regexp, "utm_" + k + "=" + utm[k]);
  35. }
  36. // Append if not
  37. else {
  38. this.href += sep + "utm_" + k + "=" + utm[k];
  39. // Change separator now since we're appending to a now existing query string
  40. sep = "&";
  41. }
  42. }
  43. }
  44. });
  45. }
  46. } catch(e) {}

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.