Skip to content Skip to sidebar Skip to footer

Back Button In Browser Not Working Properly After Using Pushstate (in Chrome)

I am using this type of line in an JS response if (history && history.pushState){ history.pushState(null, null, '<%=j home_path %>'); } but when I click back in

Solution 1:

I am currently playing around with doing

 response.headers['Vary'] = 'Accept'

which seems to solve the problem, at first look.

If anyone has the same issue, please check it and let me know

Solution 2:

You need to add a listener to the popstate event

window.onpopstate = function(event) {
    //load the page
};

When the back button is pressed the url is changed and then the popstate event is fired. It's your responsibility to load the details in your popstate listener that match the changed url.

A nice popstate example

Some browsers fire a popstate event when the page first loads, causing an infinite page loading loop. This can be avoided by adding the following check

var loadPage = window.history.state;
window.onpopstate = function(event) {
    if (loadPage) 
        //load the page
};

Then set the loadPage to true when pushState is called

history.pushState(null, null, '<%=j home_path %>');
loadPage = true;

This technique works in all browsers that support html5 history api.

Solution 3:

It happened my with sinatra & chrome.

Solved it with:

$.ajaxSetup({ cache: false });

Solution 4:

I've tested this code on my browser using a local HTML file and I've gotten a console security error:

SecurityError: The operation is insecure.
  history.pushState(null, null, '<%=j home_path %>');

I can see how manipulating browser history may be considered a potentially dangerous behaviour, so I guess you should check that this is not happening for you as well. Try using the Firebug Javascript console. It is also possible that there might be differences in behaviour between local and http:// HTML files.

Said this, for what I've seen the last element of the history array is basically the current page, so if you want to change the previous one, you might do it by using two pushState() commands - first you push the previous element that you desire, then you push the current path again. If I understood your problem correctly.

Post a Comment for "Back Button In Browser Not Working Properly After Using Pushstate (in Chrome)"