htmx icon indicating copy to clipboard operation
htmx copied to clipboard

How to push history state when using htmx.ajax()?

Open lachdoug opened this issue 1 year ago • 3 comments

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?

lachdoug avatar Apr 02 '24 23:04 lachdoug

Worth having a look at saveToHistoryCache. I haven’t checked, but my wild guess is it is only called when a trigger fires.

andryyy avatar Apr 03 '24 15:04 andryyy

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.

lachdoug avatar Apr 03 '24 20:04 lachdoug

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")
})

p-baum avatar May 07 '24 10:05 p-baum