Prevent rewind and fast forward buttons when loading a page in a single-page application

I have a one-page application in which the page is never loaded. I use # in the URL and using javascript to detect hashchange, and then update the user interface using JS and AJAX ... and I don't want the forward and back buttons to make an additional server request.

Currently, the first time a user logs on to the site, a server request is made (this is normal)

Processing by MyController#index as HTML 

My goal is for this server request to be executed only once during the userโ€™s time on the site ... every time they click on any other link, I just use the "#" in the URL to prevent a new server request ... so all my "a" tags look something like this

<a href="#page1/

The problem I am facing is that pressing the back and forward button fires my JS hashchange listener (which I want) ... but it also calls

 Processing by MyController#index as HTML //I DO NOT WANT THIS TO HAPPEN 

Here is the functionality I'm getting right now

1.) user goes to mydomain.com

2.) "Processing with MyController # index as HTML" is started and the server request is executed (THIS IS APPROVED)

3.) The user clicks the link and now the url reads mydomain.com/#page1 and I update the view using JS (THIS IS APPROVED)

4.) The user clicks on the link, and now url reads mydomain.com/#page2, and I update the view using JS (THIS IS APPROVED)

5.) The user presses BACK and now url reads mydomain.com/#page1 and I update the view using JS (THIS IS APPROVED)

6.) the server request is AUTOMATICALLY made to reload the page ("Processing by index MyController # as HTML" is called again) (THIS IS NOT OK)

How to prevent step 6 from appearing when the user clicks the back button? ... I just want the URL to change, and for me I updated my interface via JS and without a server request

Also, I use ruby โ€‹โ€‹on rails, if that helps at all.

+5
source share
3 answers

What you are trying to do is impossible. You cannot override the default behavior of browsers, for example back / forward / stop / refresh, etc.

What you can do is create your own Back and Forward buttons (and put them on the actual page) - and process their event handlers accordingly to make your AJAX calls.

+1
source

This job is great for me jQuery hashchange event

0
source

Finally it turned out. For some reason, Turbolinks caused it to reload the page whenever the "Back" or "Forward" button was clicked. I removed the Turbolinks gem from the application and now it all works fine.

0
source

Source: https://habr.com/ru/post/1235310/


All Articles