/ Published in: JavaScript
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.
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
/** * URL link updater for cross-site UTM code transposing * * Update the validURLPattern variable regular expression to match your desired pattern * that indicates link HREF values that go to the second-site. */ try { // URL pattern regular expression, change this to match your call to action links var validURLPattern = new RegExp("my-conversion-point-domain\.com"); // The search string var queryStr = document.location.search; // Only update if we have UTM parameters if(queryStr.match(/utm_campaign|utm_source|utm_medium/)){ // Build object of UTM parameters var utm = { campaign: queryStr.match(/utm_campaign/) ? queryStr.match(/utm_campaign\=([^&]*)/)[1] : "", source: queryStr.match(/utm_source/) ? queryStr.match(/utm_source\=([^&]*)/)[1] : "", medium: queryStr.match(/utm_medium/) ? queryStr.match(/utm_medium\=([^&]*)/)[1] : "" }; // Loop through all A tags and update $('a').each(function(){ // Only update if HREF refers to dtelepathy.com if(this.href.match(validURLPattern)){ // Determine starting separator var sep = this.href.indexOf("?") == -1 ? "?" : "&"; // Loop through UTM parameters to update for(var k in utm){ // Check if URL already contains this UTM parameter if(this.href.indexOf("utm_" + k) != -1){ var regexp = new RegExp("utm_" + k + "=([^&]*)"); this.href = this.href.replace(regexp, "utm_" + k + "=" + utm[k]); } // Append if not else { this.href += sep + "utm_" + k + "=" + utm[k]; // Change separator now since we're appending to a now existing query string sep = "&"; } } } }); } } catch(e) {}