JSFiddle - React, Tailwind, and code Playground
by Q4Dizzy
HTML
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/js.cookie.min.js"></script>
JavaScript
document.addEventListener("DOMContentLoaded", function() {
console.log('ready');
//input_id = ид полей (пользователи, заказы); short_id = Если значение данного параметра до первого _ необходимо добавить в доп. поле.
const utmArray = Array({
"param": "utm_source",
"input_id": [1139117, 1139159]
}, {
"param": "utm_campaign",
"input_id": [1139125, 1139161],
"short_id": [678923]
}, {
"param": "utm_medium",
"input_id": [1139153, 1139160]
}, {
"param": "utm_content",
"input_id": [1139154, 1139162]
}, {
"param": "utm_term",
"input_id": [1139155, 1139163]
}, {
"param": "vk_user_id",
"input_id": [104871]
}, {
"param": "param1",
"input_id": [104871]
}, {
"param": "mp",
"input_id": [1178904]
});
function utm_cookie() {
console.log(typeof Cookies);
if (typeof Cookies === 'undefined') return;
const url = new URL(window.location.href);
let result = [];
utmArray.forEach(function(item) {
let utm = {};
const param = item["param"],
input_id = item["input_id"],
short_id = item["short_id"],
url_param = url.searchParams.get(param);
if (url_param !== null) {
if (typeof short_id !== 'undefined') {
utm['short'] = {
value: url_param.replace(/^(.+?)_.+$/g, '$1'),
id: short_id
};
}
utm['param'] = {
name: param,
value: url_param
};
utm['input_id'] = input_id;
result.push(utm);
}
});
if (result.length) {
Cookies.set('q4_utm_params', JSON.stringify(result), {
expires: 1,
path: '/'
});
}
utm_append();
}
function utm_append() {
const utm = Cookies.get('q4_utm_params');
if (typeof utm === 'undefined') return;
const utm_cookies = JSON.parse(utm); //Array with objects
if...