Working with browser history to support back and forward buttons

Hi @jeff - sorry for the slow reply. Unfortunately the functionality is baked pretty deeply into my core product, and I can’t easily share that as a demo for security reasons. Here are the key points though:

First, my Native Libraries code contains this <script> tag:

<script>
function pushFormState(state) {
  window.history.pushState(state, null, "")
}
function getFormState() {
  return window.history.state
}
window.onpopstate = function(e) {
  anvil.call($('.content'), "js_onpopstate", window.history.state)
}
</script>

From there, I took @meredydd’s advice and have a Client Module called _BrowserHistory_client that stores a dictionary called app_history_state.

When a form loads, it executes a method that sets the _BrowserHistory_client.app_history_state dictionary and then passes it to the browser history via the pushFormState js function. The app_history_state dictionary includes everything I need to know to rebuild the current state - typically that means the name of the form and any session-specific variables. Anvil has a dedicated method that makes all this possible by allowing Python to interact with javascript functions (and the docs are great): .call_js().

Then when the onpopstate event occurs the process runs in reverse - it passes the browser history state to a Python function called js_onpopstate in the Main Form which interprets the app_history_state dictionary, clears the content panel, and loads the right form.

I won’t lie to you - it’s pretty tricky to implement the first time and will need to be customized to your specific app. But the good news is once you get it working, it’ll sort of “click” and feel much easier going forward. I’m sorry it’s not possible for me to build a working demo outside of my own application - I hope this info helps. I’m also happy to help you troubleshoot your app if you get stuck. Best of luck!

3 Likes