Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

229
Vistas
¿Cómo redirigir a otra página cuando se recarga en Javascript?

he creado una variable que contiene la ubicación actual de la página y la compara con otra y vuelve a cargar la página, pero el problema es que se ve grande y no es lo suficientemente eficiente, ya que recargar la página lleva algún tiempo mostrar la otra página web

 // let Storynumber = ["story1.html", "story2.html", "story3.html"]; let currentLocation = window.location; var i; window.onbeforeunload = function () { if (currentLocation.pathname == "/HTML/story1.html") { window.setTimeout(function () { window.location.replace("http://127.0.0.1:5500/HTML/story2.html"); console.log("Working"); }); window.onbeforeunload = null; // necessary to prevent infinite loop, that kills your browser } else if (currentLocation.pathname == "/HTML/story2.html") { window.setTimeout(function () { window.location.replace("http://127.0.0.1:5500/HTML/story3.html"); console.log("Working"); }); window.onbeforeunload = null; } else if (currentLocation.pathname == "/HTML/story3.html") { window.setTimeout(function () { window.location.replace("http://127.0.0.1:5500/HTML/story1.html"); console.log("Working"); }); window.onbeforeunload = null; } else { console.log("same page cant be reloaded"); } };
about 4 years ago · Juan Pablo Isaza
3 Respuestas
Responde la pregunta

0

para eliminar retrasos, te aconsejo que borres los métodos window.settimeout() , mira el bucle de eventos javascript te dejo el enlace aquí ( https://www.javascripttutorial.net/javascript-event-loop/#:~:text =El%20evento%20bucle%20es%20a,cola%20y%20la%20llamada%20pila.&text=En%20este%20ejemplo%2C%20el%20tiempo de espera,antes%20del%20mensaje%20%27¡Adiós!%27 ), intente con este código:

 // let Storynumber = ["story1.html", "story2.html", "story3.html"]; let currentLocation = window.location; var i; window.onbeforeunload = function () { if (currentLocation.pathname == "/HTML/story1.html") { window.location.replace("http://127.0.0.1:5500/HTML/story2.html"); console.log("Working"); window.onbeforeunload = null; // necessary to prevent infinite loop, that kills your browser } else if (currentLocation.pathname == "/HTML/story2.html") { window.location.replace("http://127.0.0.1:5500/HTML/story3.html"); console.log("Working"); window.onbeforeunload = null; } else if (currentLocation.pathname == "/HTML/story3.html") { window.location.replace("http://127.0.0.1:5500/HTML/story1.html"); console.log("Working"); window.onbeforeunload = null; } else { console.log("same page cant be reloaded"); } };
about 4 years ago · Juan Pablo Isaza Denunciar

0

Puedo ver en su código comentado que ha intentado refactorizar las declaraciones condicionales en una búsqueda de matriz, por lo que he bajado este ángulo.

También recomendaría usar addEventListener en lugar de sobrescribir directamente onbeforeunload en caso de que necesite vincular varios eventos.

Estoy trabajando bajo el supuesto de que su sitio se ejecuta en 127.0.0.1:5500 y que todas las páginas están almacenadas en el mismo directorio.

Como @salvo720 señaló en su respuesta, setTimeout no es necesario en este caso y también podría provocar demoras.

Sugeriría algo similar a esto:

 //array containing our pages const pages = ["story1.html", "story2.html", "story3.html"]; function redirectToNextPage(){ //get the current page - this grabs just the last part of the URL (eg "story1.html" instead of "HTML/story1.html" const curr = window.location.pathname.split('/').pop(); //work out which page we're on - if curr is "story1.html", this is 0, if curr is "story2.html" this is 1, etc. If it doesn't match, this is -1 let index = pages.indexOf(curr); if(index < 0 || index >= pages.length){ //if we're either non-matching or on the last element index = 0; //reset to the first one } else { index++; //go to the next one } window.removeEventListener('beforeunload', redirectToNextPage); //remove event listener window.location.replace(pages[index]); //do the redirect to the next page }); window.addEventListener('beforeunload', redirectToNextPage);

De esa manera, cuando necesite agregar "story4.html", puede agregarlo a su matriz de pages

Algo que cuestionaría es el uso del evento beforeunload para redirigir la página, pero si funciona para usted, ¡entonces funciona para usted!

about 4 years ago · Juan Pablo Isaza Denunciar

0

prueba esto:

 <!DOCTYPE html> <html> <body> <button onclick="myFunction()">Replace document</button> <script> function myFunction() { location.replace("https:www.url.com") } </script> </body> </html>

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda