Скрипты JS Cookie Работают на ПК нормально, но на телефоне - нет
Для сайта с орендой яхт, клиент захотел что бы на странице Спасиба вам, была некоторая информация об заказе, с одной страницы берется информация про дни оренды на след. выводится, на пк и планшетах все работает так как нужно, но на телефонах - нет. Я даже localStorage юзал, но тоже самое, на телефонах кидает null, как решить данную проблему?
Код с секции со страницы где берется информация:
// Function to set a cookie
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 = name + "=" + (value || "") + expires + "; path=/";
}
// Function to get a cookie
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
// Define the event handler function
function handleClick() {
setTimeout(function() {
const productUrl = window.location.pathname;
const productHandle = productUrl.split('/').filter(part => part).pop();
// Store product handle in cookie
setCookie('selectedProductHandle', productHandle, 1);
console.log("Product handle set in cookie:", productHandle);
// Redirect to the thank you page
window.location.href = '{{ shop.url }}/pages/thank-you';
}, 2000);
}
document.addEventListener('DOMContentLoaded', function() {
function searchButton() {
var buttons = document.querySelectorAll('.bookeasy-next-btn');
for (var i = 0; i < buttons.length; i++) {
if (buttons[i].innerText.trim() === 'Confirm') {
buttons[i].classList.add('gotchya');
buttons[i].addEventListener('click', handleClick); // Add event listener
} else {
buttons[i].classList.remove('gotchya');
buttons[i].removeEventListener('click', handleClick); // Remove event listener
}
}
}
function searchDays() {
numberOfDaysBlock = document.querySelectorAll(".bookeasy-booking-date-details");
console.log("Day block found: " + numberOfDaysBlock.length);
for (var i = 0; i < numberOfDaysBlock.length; i++) {
const bookingDate = numberOfDaysBlock[i].textContent;
numberOfDaysText = numberOfDaysBlock[i].textContent.trim();
const bookingDatesText = numberOfDaysBlock[i].textContent;
const bookingDatesArray = bookingDatesText.split(', ');
const numberOfDays = bookingDatesArray.length / 2;
setCookie('selectedNumberOfDays', numberOfDays, 1);
setCookie('selectedBookingDays', bookingDate, 1);
console.log("Number of days set in cookie:", numberOfDays);
console.log("Booking days set in cookie:", bookingDate);
}
}
var searchIntervalConfirm = setInterval(searchButton, 500);
var searchDaysElement = setInterval(searchDays, 500);
});
</script>
Код страницы Thank you:
// Function to get a cookie
function getCookie(name) {
var nameEQ = name + "=";
var ca = document.cookie.split(';');
for (var i = 0; i < ca.length; i++) {
var c = ca[i];
while (c.charAt(0) == ' ') c = c.substring(1, c.length);
if (c.indexOf(nameEQ) == 0) return c.substring(nameEQ.length, c.length);
}
return null;
}
document.addEventListener('DOMContentLoaded', async function() {
// Retrieve data from cookies
const productHandle = getCookie('selectedProductHandle');
const numberOfDays = getCookie('selectedNumberOfDays');
const bookingDate = getCookie('selectedBookingDays');
console.log("Retrieved product handle from cookie:", productHandle);
console.log("Retrieved number of days from cookie:", numberOfDays);
console.log("Retrieved booking date from cookie:", bookingDate);
if (productHandle) {
try {
// Fetch product details using Shopify's Storefront API or AJAX request
const productResponse = await fetch(`/products/${productHandle}.js`);
const product = await productResponse.json();
// Assuming the first variant is the one to be added to the cart
const productVariantId = product.variants[0].id;
const totalPrice = numberOfDays * product.price * 0.01;
const formattedPrice = new Intl.NumberFormat('en-US', {
style: 'currency',
currency: 'EUR',
minimumFractionDigits: 2
}).format(totalPrice);
// Create a checkout button
const checkoutButton = document.createElement('button');
const mainButton = document.createElement('button');
const bookingInfoText = document.createElement('div');
bookingInfoText.classList.add("booking-info-text");
bookingInfoText.innerHTML = `
<div class="big-colored-text"><span>Yacht: </span>${product.title}</div>
<div><span>Booking date: </span>${bookingDate}</div>
<div class="big-colored-text"><span>Price: </span>${formattedPrice}</div>
`;
checkoutButton.classList.add("custom-checkout");
mainButton.classList.add("main-button");
mainButton.innerHTML = 'To main';
checkoutButton.innerHTML = 'Pay<span class="pal">Pal</span>';
document.querySelector('.h0').innerHTML = `Thank You for booking<br>${product.title}`;
// Add event listener to the checkout button
mainButton.addEventListener('click', function(){
window.location.href = '/';
});
checkoutButton.addEventListener('click', function() {
const checkoutUrl = `/cart/${productVariantId}:${numberOfDays}`;
window.location.href = checkoutUrl;
});
document.getElementById('place-self-start-custom').appendChild(bookingInfoText);
document.getElementById('place-self-start-custom').appendChild(mainButton);
} catch (error) {
console.error("Error fetching product details:", error);
}
}
});
</script>