75 lines
2.2 KiB
JavaScript
75 lines
2.2 KiB
JavaScript
// conteo de visitas
|
|
|
|
// #######################################################
|
|
// REVISAR SI YA SE HA VISTO EL POST EL DÍA DE HOY
|
|
// #######################################################
|
|
const postId = window.location.pathname.split("/")[2]; // ID del post desde la URL
|
|
const today = new Date().toISOString().split("T")[0]; // YYYY-MM-DD
|
|
|
|
// Obtener historial de visitas del localStorage o un objeto vacío
|
|
let viewedPosts = JSON.parse(localStorage.getItem("url_viewed") || "{}");
|
|
|
|
// Revisar si ya fue visto hoy
|
|
const alreadyViewedToday = viewedPosts[postId] === today;
|
|
|
|
if (!alreadyViewedToday) {
|
|
// Actualizar localStorage
|
|
viewedPosts[postId] = today;
|
|
localStorage.setItem("url_viewed", JSON.stringify(viewedPosts));
|
|
|
|
// Enviar datos al backend
|
|
fetch("/blog/get-data", {
|
|
method: "POST",
|
|
headers: {
|
|
"Content-Type": "application/json",
|
|
},
|
|
body: JSON.stringify({ post_id: postId }),
|
|
})
|
|
.then((res) => res.json())
|
|
.then((data) => {
|
|
if (data.success) {
|
|
let viewed = document.getElementById("viewed");
|
|
let n_viewed = parseInt(viewed.innerText) + 1;
|
|
viewed.innerText = n_viewed;
|
|
}
|
|
})
|
|
.catch((err) => console.error("Error al enviar datos:", err));
|
|
}
|
|
// else {
|
|
// console.log("El post ya fue visto hoy");
|
|
// }
|
|
|
|
// #######################################################
|
|
// ACTUALIZAR CONTEO CADA MINUTO
|
|
// #######################################################
|
|
|
|
const cur_id = window.location.pathname.split("/")[2];
|
|
const viewed = document.getElementById("viewed");
|
|
|
|
async function fetchViewCount() {
|
|
try {
|
|
const res = await fetch(
|
|
window.location.origin + "/blog/api/count-post-viewed"
|
|
);
|
|
const data = await res.json();
|
|
|
|
const dict = {};
|
|
data.forEach((item) => {
|
|
dict[item.id_post] = item.count;
|
|
});
|
|
|
|
const n_viewed = parseInt(viewed.innerText);
|
|
if (dict[cur_id] !== n_viewed) {
|
|
viewed.innerText = dict[cur_id] ?? 0;
|
|
}
|
|
} catch (err) {
|
|
console.error("Error al obtener datos de visitas:", err);
|
|
}
|
|
}
|
|
|
|
// Ejecutar de inmediato
|
|
// fetchViewCount();
|
|
|
|
// Luego cada minuto
|
|
setInterval(fetchViewCount, 30000);
|