Last active
September 8, 2024 08:18
-
-
Save hunty/9b5cfe419d3dbb28e131fd100ce51d77 to your computer and use it in GitHub Desktop.
Парсит UTM метки и подставляет в скрытые поля
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
window.onload = function() { | |
// Parse the URL | |
function getParameterByName(name) { | |
var name = name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]"); | |
var regex = new RegExp("[\\?&]" + name + "=([^&#]*)"); | |
var results = regex.exec(location.search); | |
return results === null ? "" : decodeURIComponent(results[1].replace(/\+/g, " ")); | |
} | |
// Give the URL parameters variable names | |
var source = getParameterByName('utm_source'); | |
var medium = getParameterByName('utm_medium'); | |
var campaign = getParameterByName('utm_campaign'); | |
// Put the variable names into the hidden fields in the form. | |
document.getElementById("property_utm_source").value = source; | |
document.getElementById("property_utm_medium").value = medium; | |
document.getElementById("property_utm_campaign").value = campaign; | |
//U Can use it with Expertsender Forms | |
} |
Рад что пригодилось)
Самый очевидный вариант - подставлять их в запрос, т.е. можно составить ссылку таким образом:
// ссылка на новую страницу
var link = "/link_to_some_page";
// собираем метки обратно в запрос
var utm = "?utm_source=" + utm_source + "&utm_medium=" + medium + "&utm_campaign=" + campaign;
// склеиваем метки
var linkWithUtm = link + utm;
// идем на новую страницу.
window.locate(linkWithUtm);
Если ссылки уже добавлены в <a href="ссылка"/>
, то можно добавить utm к кажой ссылке, например получив весь список ссылок, и перезаписать их, или лучше добавить обработчик на onClick этих ссылок, и в нем подставлять utm к сушествующему url.
А для чего нужно это?
name.replace(/[\[]/, "\\[").replace(/[\]]/, "\\]");
без этого же прекрасно работает :)
Так ловим:
function getUTMParams() {
const urlParams = new URLSearchParams(window.location.search);
const utms = {
utm_source: urlParams.get('utm_source'),
utm_medium: urlParams.get('utm_medium'),
utm_campaign: urlParams.get('utm_campaign'),
utm_term: urlParams.get('utm_term'),
utm_content: urlParams.get('utm_content')
};
// Сохраняем UTM-метки в sessionStorage для дальнейшей передачи
sessionStorage.setItem('utms', JSON.stringify(utms));
return utms;
}
// Получаем UTM-метки
const utmParams = getUTMParams();
Так принимаем на другой странице:
<?php
$utm_source = $_SESSION['utms']['utm_source'];
$utm_medium = $_SESSION['utms']['utm_medium'];
$utm_campaign = $_SESSION['utms']['utm_campaign'];
?>
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Спасибо огромное - так работает с ajax. Подскажите, а как метки можно сохранить при переходы на другие страницы?