16

Is there a function that can be called to prevent the browser from recording a back history entry when changing the hash value?

I am writing a simple javascript gallery that changes the browser url without reloading the page as the user moves through each image.

This is done by setting the location.hash to the unique ID of the image.

window.location.hash = imageID;

The problem is when the user hits the browser back button, they must move backwards through every image like it was a page load.

If they rotated through 20 images using the gallery, they must click back 21 times to get back to the previous page.

How can I prevent a back history from being recorded with javascript?

2 Answers 2

34

window.location.replace will let you set the url without adding it to the browser history.

var baseUrl = window.location.href.split('#')[0];
window.location.replace( baseUrl + '#' + imageID );

documentation

3
  • Although this also answers my question, I gave the answer to charles because he answered it first. Thanks. Jul 13, 2012 at 16:04
  • @GeorgeFilippakos It doesn't work like that - accepted answer should be the one that answers the best your question. Clearly this one is better.
    – Déjà vu
    Apr 5, 2018 at 5:21
  • You don't even need to compute the base URL. You can just to window.location.replace( '#' + imageID ); Oct 24, 2021 at 2:37
5

You can use replaceState().

Before you change the hash you save the history, then you change your hash, finally you replace the history with the one you saved.

Alternatively you can use popState Event.

1
  • Thanks for pointing me in the right direction. This method also allows me to do away with the # altogether :) Jul 13, 2012 at 16:04

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.