According to Htmx
doc for hx-push-url
:
The hx-push-url attribute allows you to push a URL into the browser location history. This creates a new history entry, allowing navigation with the browser’s back and forward buttons. htmx snapshots the current DOM and saves it into its history cache, and restores from this cache on navigation.
This causes previous pages to just get restored and not reloaded and If I remove hx-push-url
, navigation doesn't match with user's expectation. Almost all of my page navigations are with Htmx
and I sometimes want pages to reload on navigating back. Is there a way achieve this with Htmx? Or could be that I'm misusing Htmx?
HTMX does not provide an official way to prevent this behavior, yet. However with a little manual work we can force HTMX to make a full page refresh. HTMX stores the page in the localStorage
under htmx-history-cache
key. So we can use the htmx:pushedIntoHistory
event (~ the page has been saved to the history) to delete this key completely, forcing HTMX to make a new request to the server.
<script>
document.body.addEventListener('htmx:pushedIntoHistory', (evt) => {
localStorage.removeItem('htmx-history-cache')
})
</script>
However, by default HTMX will make an AJAX request instead a full page reload. To force a full reload, we also need to set refreshOnHistoryMiss
to true
:
<meta name="htmx-config" content='{"refreshOnHistoryMiss":"true"}' />