Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Preventing back and forward buttons from reloading the page in a single page app

I have a single page app in which the page is never unloaded. I am using the # in the url and using javascript to detect the hashchange and then updating the UI using JS and AJAX... and I do not want the forward and back buttons to make an extra request to the server.

Currently, the first time the user initially comes to the site, a server request is made (which is OK)

Processing by MyController#index as HTML

My goal is for this server request to only happen once during the users time at 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 like something like this

<a href="#page1/

The issue I am having is that clicking the back and forward button triggers my JS hashchange listener (which is what I want)... but it also calls

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

Here is the functionality I am currently getting

1.) user navigates to mydomain.com

2.) "Processing by MyController#index as HTML" is launched and a server request is made (THIS IS OK)

3.) User clicks a link and now the url reads mydomain.com/#page1 and I update the view with JS (THIS IS OK)

4.) User clicks a link and now the url reads mydomain.com/#page2 and I update the view with JS (THIS IS OK)

5.) User clicks BACK and now the url reads mydomain.com/#page1 and I update the view with JS (THIS IS OK)

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

How do I prevent step 6 from occuring when the user clicks the back button??... I just want the url to change and for me to update my UI via JS and no server request

Also, I am using ruby on rails if this helps at all.

like image 911
Yaseen Aniss Avatar asked Nov 10 '22 02:11

Yaseen Aniss


1 Answers

What you're trying to do is impossible. You can't override the default behavior of browser buttons like back/forward/stop/refresh, etc.

What you could do is create your own Back and Forward buttons (and place them on the actual page, itself) - and code their event handlers accordingly to make your AJAX calls.

like image 141
Stan Shaw Avatar answered Nov 14 '22 21:11

Stan Shaw