-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathScript novo - utm_term
More file actions
200 lines (175 loc) · 7.6 KB
/
Script novo - utm_term
File metadata and controls
200 lines (175 loc) · 7.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
<script>
(function () {
// Função para obter o valor de um parâmetro da URL
function getParameterByName(name, url) {
if (!url) url = window.location.href;
name = name.replace(/[\[\]]/g, "\\$&");
var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
results = regex.exec(url);
if (!results) return null;
if (!results[2]) return '';
return decodeURIComponent(results[2].replace(/\+/g, " "));
}
// Função para definir um cookie com domínio
function setCookie(cookieName, cookieValue, expirationTime) {
var cookiePath = "/";
expirationTime = expirationTime * 1000; // Converter para milissegundos
var date = new Date();
var now = date.getTime();
date.setTime(now + expirationTime);
var expires = date.toUTCString();
var domain = ".seudominio.com";
document.cookie = cookieName + "=" + cookieValue + "; expires=" + expires + "; path=" + cookiePath + "; domain=" + domain;
}
// Função para obter o valor de um cookie pelo nome
function getCookieValue(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i].trim();
if (c.indexOf(nameEQ) === 0) return c.substring(nameEQ.length);
}
return null;
}
// Função para obter host do referrer
function getReferrerHost() {
var a = document.createElement('a');
a.href = document.referrer;
return a.hostname;
}
// Definir nome do cookie index e obter valor
var cookieName = "index";
var indexValue = getCookieValue(cookieName);
// fallback para localStorage
if (!indexValue) {
indexValue = localStorage.getItem(cookieName);
}
// valor padrão via GTM
if (!indexValue || indexValue === '') {
indexValue = {{event_id}};
}
// Armazenar index em cookie/storage
var expiration = 34560000; // um ano em segundos
setCookie(cookieName, indexValue, expiration);
localStorage.setItem(cookieName, indexValue);
sessionStorage.setItem(cookieName, indexValue);
// Salvar data de entrada
var dateCookie = "entry_date";
var entryDate = getCookieValue(dateCookie);
if (!entryDate) {
entryDate = new Date().getTime().toString();
setCookie(dateCookie, entryDate, expiration);
localStorage.setItem(dateCookie, entryDate);
sessionStorage.setItem(dateCookie, entryDate);
}
// Parâmetros de anúncio
var adParams = ['fbclid', 'gclid'];
var isAd = false;
for (var i = 0; i < adParams.length; i++) {
if (getParameterByName(adParams[i])) {
isAd = true;
break;
}
}
// Capturar UTMs com fallback de referrer para utm_source
var utmSource = getParameterByName('utm_source')
|| (document.referrer ? (getParameterByName('utm_source', document.referrer) || getReferrerHost()) : 'direto');
var utmMedium = getParameterByName('utm_medium');
var utmCampaign = getParameterByName('utm_campaign');
var utmTerm = getParameterByName('utm_term');
// Gravar UTMs em cookies (exceto orgânico)
if ((isAd || utmSource) && utmSource.toLowerCase() !== 'organico') {
if (utmSource) setCookie('cookieUtmSource', utmSource, expiration * 2);
if (utmMedium) setCookie('cookieUtmMedium', utmMedium, expiration * 2);
if (utmCampaign) setCookie('cookieUtmCampaign', utmCampaign, expiration * 2);
if (utmTerm) setCookie('cookieUtmTerm', utmTerm, expiration * 2);
}
// Parametros atuais da URL
var currentSearch = window.location.search.substring(1);
var paramsObj = {};
if (currentSearch) {
currentSearch.split('&').forEach(function(pair) {
var p = pair.split('=');
if (p.length === 2) paramsObj[decodeURIComponent(p[0])] = decodeURIComponent(p[1]);
});
}
// ── FORÇAR utm_term PARA indexValue SEM CONDIÇÃO ──
paramsObj.utm_term = indexValue;
// ── PASSAR COOKIES DE UTM PARA utm_content ──
if (!paramsObj.utm_content) {
var contentArr = [];
['cookieUtmSource','cookieUtmMedium','cookieUtmCampaign','cookieUtmTerm'].forEach(function(c) {
var v = getCookieValue(c);
if (v) contentArr.push(v);
});
if (contentArr.length) paramsObj.utm_content = contentArr.join('|');
}
// Garantir utm_source na URL
if (!paramsObj.utm_source) {
paramsObj.utm_source = utmSource;
}
// Reconstruir querystring SEMPRE que utm_term for sobrescrito
var modified = true;
if (modified) {
var newQ = '?';
var first = true;
for (var k in paramsObj) {
if (first) first = false;
else newQ += '&';
newQ += encodeURIComponent(k) + '=' + encodeURIComponent(paramsObj[k]);
}
var newUrl = window.location.protocol + '//' + window.location.host + window.location.pathname + newQ + window.location.hash;
window.history.replaceState(null, null, newUrl);
}
// Atualizar links e iframes
function updateHref(el, href) {
try {
var a = document.createElement('a');
a.href = href;
var searchParams = new URLSearchParams(a.search);
// CAPTURAR UTMs DA URL ATUAL
var currentParams = new URLSearchParams(window.location.search);
// Preservar utm_source
if (currentParams.has('utm_source') && !searchParams.has('utm_source')) {
searchParams.set('utm_source', currentParams.get('utm_source'));
} else if (!searchParams.has('utm_source')) {
searchParams.set('utm_source', utmSource);
}
// Preservar utm_medium
if (currentParams.has('utm_medium') && !searchParams.has('utm_medium')) {
searchParams.set('utm_medium', currentParams.get('utm_medium'));
}
// Preservar utm_campaign
if (currentParams.has('utm_campaign') && !searchParams.has('utm_campaign')) {
searchParams.set('utm_campaign', currentParams.get('utm_campaign'));
}
// ── PASSAR COOKIES DE UTM PARA utm_content ──
if (currentParams.has('utm_content') && !searchParams.has('utm_content')) {
searchParams.set('utm_content', currentParams.get('utm_content'));
} else if (!searchParams.has('utm_content')) {
var cv = [];
['cookieUtmSource','cookieUtmMedium','cookieUtmCampaign','cookieUtmTerm'].forEach(function(c) {
var v = getCookieValue(c);
if (v) cv.push(v);
});
if (cv.length) searchParams.set('utm_content', cv.join('|'));
}
// ── FORÇA utm_term PARA indexValue (sempre sobrescreve) ──
searchParams.set('utm_term', indexValue);
return a.protocol + '//' + a.host + a.pathname + '?' + searchParams.toString() + a.hash;
} catch(e) {
console.error('updateHref error', e);
return href;
}
}
var links = document.getElementsByTagName('a');
for (var j = 0; j < links.length; j++) {
links[j].href = updateHref(links[j], links[j].href);
}
var iframes = document.getElementsByTagName('iframe');
for (var j = 0; j < iframes.length; j++) {
var srcAtt = iframes[j].getAttribute('data-src') || iframes[j].src;
iframes[j].setAttribute('data-src', updateHref(iframes[j], srcAtt));
}
})();
</script>