Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // First GTM code
- (function() {
- function setCookie(name, value, days) {
- var expires = "";
- if (days) {
- var date = new Date();
- date.setTime(date.getTime() + (days * 24 * 60 * 60 * 1000));
- expires = "; expires=" + date.toUTCString();
- }
- document.cookie = "g_" + name + "=" + encodeURIComponent(value) + expires + "; path=/; Secure; SameSite=Lax";
- }
- function getQueryParam(param) {
- var urlParams = new RegExp('[?&]' + param + '=([^&#]*)').exec(window.location.search);
- return urlParams ? decodeURIComponent(urlParams[1].replace(/\+/g, ' ')) : null;
- }
- var utmParams = ['utm_source', 'utm_medium', 'utm_campaign', 'utm_term', 'utm_content', 'utm_id'];
- var utmIdExists = getQueryParam('utm_id') !== null;
- var gclidExists = getQueryParam('gclid') !== null;
- if (utmIdExists || gclidExists) { // Fire only if utm_id or gclid is present
- utmParams.forEach(function(param) {
- var value = getQueryParam(param);
- if (value) {
- setCookie(param, value, 730); // 2 years expiry
- }
- });
- }
- // Notify GTM that cookies are set
- window.utmCookiesSet = true;
- })();
- // Second GTM code
- (function() {
- function getCookie(name) {
- var match = document.cookie.match(new RegExp('(?:^|;\\s*)g_' + name + '=([^;]*)'));
- return match ? decodeURIComponent(match[1]) : "";
- }
- function waitForCookies(callback) {
- if (window.utmCookiesSet) {
- callback();
- } else {
- setTimeout(function() { waitForCookies(callback); }, 100); // Retry every 100ms
- }
- }
- waitForCookies(function() {
- var utm_source = getCookie("utm_source");
- var utm_medium = getCookie("utm_medium");
- var utm_campaign = getCookie("utm_campaign");
- var utm_term = getCookie("utm_term");
- var utm_content = getCookie("utm_content");
- var utm_id = getCookie("utm_id");
- if (!utm_campaign) {
- console.warn("No g_utm_campaign cookie found. Skipping link updates.");
- return;
- }
- var utm_query = `?utm_source=${encodeURIComponent(utm_source)}&utm_medium=${encodeURIComponent(utm_medium)}&utm_campaign=${encodeURIComponent(utm_campaign)}&utm_term=${encodeURIComponent(utm_term)}&utm_content=${encodeURIComponent(utm_content)}&utm_id=${encodeURIComponent(utm_id)}`;
- var links = document.querySelectorAll("a[href]");
- links.forEach(function(link) {
- var href = link.href;
- if ((href.includes("/contact-us/") || href.includes("/products/") || href.includes("/ray-the-sheep/") || href.includes("share.hsforms.com"))
- && !href.includes("utm_source")) { // Avoid duplicate UTMs
- link.href = href.split("?")[0] + utm_query;
- console.log("Updated link:", link.href);
- }
- });
- console.log("Selected links updated with UTM parameters.");
- });
- })();
Advertisement
Add Comment
Please, Sign In to add comment