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

262
Vistas
How to prevent history.back() to return back to external website?

So I am trying to make a back button using onclick="history.back()". But the thing is when I enter my website using an external link, and press the back button, it takes me back to the previous page which is external. I know that it has been programmed to do so. But is there any way to prevent it from taking users back to the external website?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

One way would be to store in the sessionStorage the history.length value that you received when first visiting the page.

Then you will store the current index in the history.state. Once you reach back the initial index, you'd prevent the history to go back.

// To be executed on all the pages of your domain

// check if we already saved it
let min_index = sessionStorage.getItem("minHistoryIndex");
// otherwise
if (min_index === null) {
  // store it
  min_index = history.length;
  sessionStorage.setItem("minHistoryIndex", min_index);
}
// first time we come to this history status
if (!history.state ) {
  history.replaceState({ index: history.length }, "");
}

const button = document.querySelector("button");
// if we reached the limit saved in sessionStorage
if (history.state.index === +min_index) {
  button.disabled = true;
  button.title = "Going back once more would take you out of our website";
}
else {
  button.onclick = (evt) => history.back();
}

Live demo - source

One problem with this is that if your user decides to go to an other origin from your page and then go back to it manually, you could go back to that external domain, but I guess it's such a corner case that it can be accepted in most cases.

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