Para ejecutar un evento cuando cambia el path de la URL en una página web, puedes usar las siguientes técnicas en JavaScript:
1. Usar window.onpopstate (para cambios en el historial)
- Detecta cambios en la URL cuando se usa
history.pushState() o history.replaceState().
- También se activa al usar los botones de "Atrás" o "Adelante" del navegador.
window.onpopstate = function(event) {
console.log("La URL cambió a:", window.location.pathname);
// Ejecuta tu evento aquí
};
2. Usar window.addEventListener("popstate", ...) (alternativa moderna)
window.addEventListener("popstate", function(event) {
console.log("Nueva URL:", window.location.pathname);
// Ejecuta tu evento aquí
});
3. Usar MutationObserver (para cambios en el DOM que afecten la URL)
- Útil si la URL cambia debido a manipulaciones del DOM (como en frameworks como React o Vue).
const observer = new MutationObserver(function(mutations) {
if (window.location.pathname !== lastPath) {
lastPath = window.location.pathname;
console.log("La URL cambió a:", lastPath);
// Ejecuta tu evento aquí
}
});
let lastPath = window.location.pathname;
observer.observe(document.body, { childList: true, subtree: true });
4. Usar setInterval (solución simple pero menos eficiente)
- Verifica periódicamente si la URL cambió.
let lastPath = window.location.pathname;
setInterval(function() {
if (window.location.pathname !== lastPath) {
lastPath = window.location.pathname;
console.log("La URL cambió a:", lastPath);
// Ejecuta tu evento aquí
}
}, 100); // Verifica cada 100ms
5. Usar history.pushState o history.replaceState (si controlas los cambios)
- Si tú mismo modificas la URL, puedes ejecutar tu evento justo después.
const originalPushState = history.pushState;
history.pushState = function(state, title, path) {
originalPushState.apply(history, arguments);
console.log("La URL cambió a:", path);
// Ejecuta tu evento aquí
};
Recomendación:
- Si usas un framework moderno (React, Vue, Angular), es mejor usar sus herramientas nativas (como
useEffect en React o watch en Vue).
- Si trabajas con JavaScript puro,
window.onpopstate o MutationObserver son las opciones más limpias.
¿Necesitas ayuda con algún caso en específico? 😊