How to trigger live navigation from JS?

Hi there! I’m building a small personal web-app with LiveView, and have been experimenting with some navigation keyboard shortcuts. I’d really like to be able to have certain keyboard shortcuts trigger live redirects to other pages, but I’m struggling to find a way to do this from the javascript side.

To get things temporarily working, I’ve been using the LiveSocket’s private historyRedirect function. This seems to work reasonably well, though I’m getting some rather unexpected behaviour when using the browser back button. I was also able to get things working using the LiveSocket’s public execJS function by passing it the “navigate” kind and appropriate arguments, but unfortunately was still having issues with the browser’s back button seeming to go two pages back, rather than just to the immediately previous page.

I was wondering if anyone had any advice on a proper way to go about triggering a live redirect from the JS side of things?


It feels like the strange back-button behaviour is likely related to me going about things the wrong way, as it works exactly as expected when clicking on navigate links in the UI. Happy to provide more details if it would be helpful! :smiley:

2 Likes

It does seem like this should be easier, but every example I’ve seen of redirecting from the client side that is not a link involved pushEvent + server side redirect. Would love to be corrected though

Does the Phoenix.LiveView.JS.navigate/1 do what you need? Phoenix.LiveView.JS — Phoenix LiveView v0.18.15

You can bind those to the phx-* event handlers:

<input phx-keydown={JS.navigate(to: "/")}>