Imagine a scenario where a page contains only the following script:
<script type="text/javascript">
window.location.hash = 'testing';
window.history.back();
</script>
When you navigate to google.com and then load this page, you'll notice the hash changing in the address bar, but the page immediately redirects back to Google. Ideally, the #testing
hash should just be removed.
If I introduce a slight delay using a setTimeout function, everything works as intended:
<script type="text/javascript">
setTimeout(function () {
window.location.hash = 'testing';
window.history.back();
}, 1000);
</script>
In this case, the address bar momentarily displays the #testing
hash before it disappears.
This indicates that modifications to the location.hash are reflected in the history api with some latency. There seems to be an event triggering this behavior change.
After reviewing the available events on mdn, I came across:
pageshow
: The pageshow event occurs when a session history entry is being accessed. (This covers back/forward navigation and the initial page showing after the onload event.)
load
: The load event is triggered once a resource and its dependencies have finished loading.
However, neither of these events resolves the issue. I attempted:
<script type="text/javascript">
window.addEventListener('pageshow', function () {
window.location.hash = 'testing';
window.history.back();
}, false);
</script>
and repeated the process with the load
event. The result remains the same - the address bar flickers with the #testing
hash before reverting to the previous page.
How can I determine if it's safe to modify the location.hash
successfully?