htmx
htmx copied to clipboard
How to push history state when using htmx.ajax()?
I'd like to update browser history after a htmx.ajax() call.
htmx.ajax() does not have an option to update history state automatically, like we have when using the hx-push-url attribute.
I would have expected this to work.
htmx.ajax("GET", url, {
target: "#content",
select: "#content",
swap: "outerHTML",
}).then(() => {
history.pushState({ htmx: true }, "", url);
});
However, when back button is pressed after updating content, the browser location updates, but the previous content is not displayed.
Is there an idiomatic way to integrate htmx.ajax() and history.pushState?
Worth having a look at saveToHistoryCache. I haven’t checked, but my wild guess is it is only called when a trigger fires.
Is that function exposed in the public API? I can see that function in the source code, but can't see how to access it from my application js.
Set the source attribute to the element where you want to read hx-push-url (or any other setting) from:
htmx.ajax("GET", url, {
target: "#content",
select: "#content",
swap: "outerHTML",
source: htmx.find("#my-pretend-source-elem")
})