PageSourceSearch

https://lk.biorich.com/biorich2.js

js biorich.com collected 2026-09-30 02:35:04 UTC 7,024 bytes, 199 lines download raw bytes

1/**
2 * description - скрипт для обработки добавления элементов в корзину старой версии сайта
3 *
4 */
5const currentDomain = window.location.hostname;
6
7const isDev = currentDomain.includes('.tech');
8const isOldCart =
9  window.location.href.includes('/checkout') || window.location.href.includes('/biorich.com/cart/');
10
11const cookieStoreKey = 'cartItems';
12const CART_URL = `https://lk.biorich.${isDev ? 'tech' : 'com'}/public-cart`;
13const domain = `biorich.${isDev ? 'tech' : 'com'}`;
14const cookie_life_days = 365;
15
16if (isOldCart) {
17  window.open(CART_URL, '_self');
18}
19
20// Функция для получения текущих элементов корзины из cookies
21function getCartItems() {
22  const decodedCookie = decodeURIComponent(document.cookie);
23  const cookieArray = decodedCookie.split(';');
24  const cartCookie = cookieArray.find((cookie) => cookie.trim().startsWith(`${cookieStoreKey}=`));
25  return cartCookie ? JSON.parse(cartCookie.split('=')[1] || '[]') : [];
26}
27
28// Функция для сохранения элементов корзины в cookies
29function saveCartItems(items) {
30  const expirationDate = new Date();
31  expirationDate.setDate(expirationDate.getDate() + cookie_life_days);
32  const cookieValue =
33    encodeURIComponent(JSON.stringify(items)) +
34    (cookie_life_days ? `; expires=${expirationDate.toUTCString()}` : '');
35  document.cookie = `${cookieStoreKey}=${cookieValue}; domain=${domain}; path=/`;
36  setCartItemsCount();
37}
38
39// Функция получения counter в подробной карточке товара
40/**
41 *
42 * @param targetTagName
43 */
44function getCount(targetTagName) {
45  if (targetTagName === 'BUTTON') {
46    const elements = document.getElementsByClassName('input-text qty');
47    if (elements[0]) {
48      return elements?.[0]?.value ? Number(elements?.[0]?.value) : 1;
49    }
50  } else {
51    return 1;
52  }
53  return 1;
54}
55
56// Функция для обработки кликов по кнопкам добавления в корзину
57/**
58 *
59 * @param event
60 */
61function handleAddToCartClick(event) {
62  const { target } = event;
63  if (target.classList.contains('add_to_cart_button')) {
64    const productId = target.getAttribute('data-product_id') || target.getAttribute('value');
65    const cartItems = getCartItems();
66    const existingItem = cartItems.find((item) => item.id === String(productId));
67    const counter = getCount(target.tagName);
68
69    if (existingItem) {
70      existingItem.count += counter;
71    } else {
72      const newItem = {
73        id: String(productId),
74        count: counter,
75      };
76      cartItems.push(newItem);
77    }
78
79    saveCartItems(cartItems);
80    console.log('Updated cart items:', cartItems);
81  }
82}
83
84/** */
85function setCartItemsCount() {
86  const cartCount = document.querySelectorAll('.cart-clone .min-pcs')?.[0];
87  if (cartCount) {
88    cartCount.innerHTML = String(getCartItems().reduce((acc, item) => item.count + acc, 0));
89  }
90}
91
92/** */
93function replaceCartButton() {
94  // Находим оригинальный элемент по его id
95  const originalCartButton = document.querySelectorAll('.cart-contents')[0];
96
97  // Создаем клон оригинального элемента
98  const cloneCartButtonElement = originalCartButton.cloneNode(true);
99
100  // Добавляем класс для стилизации
101  cloneCartButtonElement.classList.remove('cart-contents');
102  cloneCartButtonElement.classList.add('cart-clone');
103
104  // Вставляем клон после оригинала
105  originalCartButton.insertAdjacentElement('afterend', cloneCartButtonElement);
106  originalCartButton.remove();
107
108  cloneCartButtonElement.addEventListener('click', (event) => {
109    event.preventDefault();
110    event.stopPropagation();
111    window.open(CART_URL, '_self');
112  });
113
114  console.log('cart has been initied');
115}
116
117// Назначение обработчика кликов для всего документа
118document.addEventListener('click', handleAddToCartClick);
119
120const initScript = () => {
121  replaceCartButton();
122  setCartItemsCount();
123  replaceButtonProducts();
124  addCartRedirect();
125  subscribeCookies();
126  console.log('Стартуем скрипт');
127};
128// Функция для получения значения куки по имени
129function getCookie(cookieName) {
130  const name = cookieName + '=';
131  const decodedCookie = decodeURIComponent(document.cookie);
132  const cookieArray = decodedCookie.split(';');
133  for (const element of cookieArray) {
134    let cookie = element.trim();
135    if (cookie.indexOf(name) === 0) {
136      return cookie.substring(name.length, cookie.length);
137    }
138  }
139  return '';
140}
141/**
142 * @description       - подпись на куки путем чтение раз в interval
143 * @param cookieName
144 * @param callback
145 * @param interval
146 */
147function subscribeToCookieChanges(cookieName, callback, interval = 1000) {
148  let lastCookieValue = getCookie(cookieName);
149  setInterval(() => {
150    const currentCookieValue = getCookie(cookieName);
151    if (currentCookieValue !== lastCookieValue) {
152      callback(currentCookieValue);
153      lastCookieValue = currentCookieValue;
154    }
155  }, interval);
156}
157/**
158 * @description - Заменяет на сайте кнопки "В корзину" и "Добавлено" на основе кук. Логика - найти таблицу с товарами
159 * перебрать каждый товар и посмотреть есть ли он в корзине (Нужен поиск таким образом, тк, если товары были в корзине
160 * уже, то их не очистить, пока не зайдешь в старую корзину, тк устаналивается значение из АПИ WP)
161 */
162const replaceButtonProducts = () => {
163  const products = document.querySelector('.grid_m');
164  if (products) {
165    const cardItems = getCartItems();
166    products.childNodes.forEach((element) => {
167      const targetElement = element.childNodes[3]?.querySelector('a');
168      if (targetElement) {
169        const productID = targetElement.getAttribute('data-product_id');
170        const itemInCart = cardItems.some((item) => item.id === productID);
171        targetElement.text = itemInCart ? 'Добавлено' : 'В корзину';
172      }
173    });
174  }
175};
176
177/**
178 * @description - берет все ссылки a и заменяет href, если есть вход на cart/checkout
179 */
180function addCartRedirect() {
181  document.addEventListener('DOMContentLoaded', function () {
182    const allLinks = document.querySelectorAll('a');
183    allLinks.forEach(function (link) {
184      if (link.href.includes('cart') || link.href.includes('checkout')) {
185        link.href = CART_URL;
186      }
187    });
188  });
189}
190
191function subscribeCookies() {
192  subscribeToCookieChanges(cookieStoreKey, () => {
193    setCartItemsCount();
194    replaceButtonProducts();
195  });
196  console.log('Стартуем отслеживание кукисов');
197}
198
199initScript();

Line numbers count LF bytes from the start of the resource, as the search results do. Vendor segments are library code the classifier recognised; they are stored but not indexed. Bytes are shown as Latin1 characters, one per byte.