Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

272
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda