Skip to content

Commit

Permalink
Merge pull request #14631 from britneywwc/utm-cookies
Browse files Browse the repository at this point in the history
feat: Implement utms cookie to store utm parameters in a session
  • Loading branch information
britneywwc authored Jan 15, 2025
2 parents be68768 + 0393a58 commit 467b6fd
Show file tree
Hide file tree
Showing 3 changed files with 51 additions and 2 deletions.
32 changes: 32 additions & 0 deletions static/js/src/cookie-policy-with-callback.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,3 +34,35 @@ function setUserId() {
}
}
}

setUtms();

function setUtmCookies(urlParams) {
let utmParams = "";
urlParams.forEach((value, key) => {
if (key.startsWith("utm_")) {
utmParams += key + ":" + value + "&";
}
});
if (utmParams.length > 0) {
if (utmParams.endsWith("&")) {
utmParams = utmParams.slice(0, -1);
}
document.cookie =
"utms=" + encodeURIComponent(utmParams) + ";max-age=86400;path=/;";
}
}

function setUtms() {
let utmCookies = getCookie("utms");
const urlParams = new URLSearchParams(window.location.search);
if (urlParams.size > 0) {
setUtmCookies(urlParams);
} else if (utmCookies) {
const referrer = document.referrer;
const currentHost = window.location.host;
if (!referrer.includes(currentHost)) {
document.cookie = "utms=;max-age=0;path=/;";
}
}
}
2 changes: 1 addition & 1 deletion static/js/src/prepare-form-inputs.js
Original file line number Diff line number Diff line change
Expand Up @@ -120,7 +120,7 @@ function isValidNumber(number) {
*/
function resetErrorState(errorElement, phoneInput) {
phoneInput?.parentNode?.parentNode.classList.remove("is-error");
phoneInput.removeAttribute("aria-describedby", "invalid-number-message");
phoneInput?.removeAttribute("aria-describedby", "invalid-number-message");
if (errorElement.parentNode) {
errorElement.remove();
}
Expand Down
19 changes: 18 additions & 1 deletion webapp/views.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,7 +17,7 @@
from geolite2 import geolite2
from requests import Session
from requests.exceptions import HTTPError
from urllib.parse import quote
from urllib.parse import quote, unquote

from canonicalwebteam.search.models import get_search_results
from canonicalwebteam.search.views import NoAPIKeyError
Expand Down Expand Up @@ -993,6 +993,23 @@ def marketo_submit():
],
}

encoded_utms = flask.request.cookies.get("utms")
if encoded_utms:
utms = unquote(encoded_utms)
utm_dict = dict(i.split(":", 1) for i in utms.split("&"))
approved_utms = [
"utm_source",
"utm_medium",
"utm_campaign",
"utm_content",
"utm_term",
]
for k, v in utm_dict.items():
if k in approved_utms:
if k == "utm_content":
k = "utmcontent"
enrichment_fields[k] = v

try:
ip_location = ip_reader.get(client_ip)
if ip_location and "country" in ip_location:
Expand Down

0 comments on commit 467b6fd

Please sign in to comment.