Carry URL information throughout site
New here? Learn about Bountify and follow @bountify to get notified of new bounties! x

I would like to keep all manual tracking information within the URL of a site as I browse through it. How do I maintain this information?

Example:
I land on a website from an advertising source. The domain on the initial page looks like this:
http://www.drivearnold.com/?utm_source=amazon&utm_medium=banner&utm_campaign=hats

When I click to other pages within that site, everything after the ? in the URL disappears. I'd like to carry that throughout the session. Is it possible? How do I do that?

You can set cookies, HTML5 localstorage, or just pass the data along the other links. (There are probably other ways to do this, but these 3 are the most commonly used.)
alex over 6 years ago
awarded to Wikimedia

Crowdsource coding tasks.

2 Solutions


Create a variable in your session and store this value there

echo '<a href="'. $_SERVER['HTTP_REFERER'] . '">URL</a>';

Append to All Links

This is an example using jQuery that will append the data from utm_source, utm_medium, and utm_campaignto all links (<a>) on the page.

So a link that looks like <a href="http://site.com/"> will turn into this <a href="http://site.com/?utm_source=amazon&utm_medium=banner&utm_campaign=hats">.

var querystring = "utm_source="+getURLParameter(utm_source)+"&utm_medium="+getURLParameter(utm_medium)+"&utm_campaign="+getURLParameter(utm_campaign)+;

// Functions Requires jQuery
// Function From: http://stackoverflow.com/questions/11526102/jquery-append-querystring-to-all-links
$("a").each(function() {
    var href = $(this).attr("href");
    href += (href.match("?") ? "&" : "?") + querystring;
    $(this).attr("href", href);
});

// Function From: http://stackoverflow.com/a/8604927
function getURLParameter(name) {
    return decodeURIComponent(
        (location.search.match(RegExp("[?|&]"+name+'=(.+?)(&|$)'))||[,null])[1]
    );
}

Local Storage

Here is an example using HTML5 Local Storage which will save utm_source, utm_medium, and utm_campaign. The data saved to Local Storage can be called from the same base url, i.e. it can be saved from site.com/index.php and accessed from site.com/page.php.

if(typeof(Storage)!== "undefined") {
    localStorage.utm_source = getURLParameter(utm_source);
    localStorage.utm_medium = getURLParameter(utm_medium);
    localStorage.utm_campaign = getURLParameter(utm_campaign);

    console.log("UTM_Source: "+localStorage.utm_source);
    console.log("UTM_Medium: "+localStorage.utm_medium);
    console.log("UTM_Campaign: "+localStorage.utm_campaign);
} else {
    // Browser Doesn't Support LocalStorage
    // Use Another Method (Cookies, etc.)
}

// Function From: http://stackoverflow.com/a/8604927
// Function Requires jQuery
function getURLParameter(name) {
    return decodeURIComponent(
        (location.search.match(RegExp("[?|&]"+name+'=(.+?)(&|$)'))||[,null])[1]
    );
}
View Timeline