javascriptphpbrowser-historyhtml5-historyreferer

How to implement a "History" Back-Button


I have a website showing the details of a client (www.mysite.com/client.php?id=1234). This page can be loaded from different locations within the website.

I want to have a "Back-Button" to the previous page.

My first solution was to use <a href="javascript:window.history.back();">back</a>. This is working generally fine.

But of cause, the client's details can be edited (by an bootstrap modal). Once "save" is pushed, the data are stored and the client's details (www.mysite.com/client.php?id=1234) are loaded again to show the correct (updated) data. Now the above solution doesn't work fine anymore as the "Back-Button" needs to be pushed twice to get to the "entry"-site.

Questions:

1) Is the JavaScript-Solution the correct one, or do I have to implement a server-side array to track the history-log (sounds quite heavy)?

2) Is anything wrong with the reload of the site after update? Or can I prevent a client-side history-log in that case?

3) Any other ideas?

Thanks for your support!

Tim


Solution

  • The back button normally brings the user back to the previous URL. The browser may cache the page contents and show outdated data. You could tell the browser not to cache specific pages.

    <meta http-equiv="Cache-Control" content="no-cache, no-store, must-revalidate" />
    <meta http-equiv="Pragma" content="no-cache" />
    <meta http-equiv="Expires" content="0" />
    

    Furthermore, any user-specific solution will fail if one user is modifying the data and another is just viewing it. You must force fetching the data from server every time a page is loaded. Hence, no-cache headers

    UPDATE:

    To bring users back where you want, you could use another parameter specifying the "back" destination URL. E.g.

     www.mysite.com/client.php?id=1234&backdestination=list.php%3Fshow%3D123 
     //list.php?show=123
    

    then, on the page create a button/link and use the value from backdestination

    UPDATE 2:

    You could check window.History API and specifically replaceState method. It technically allows you to specify where "back" is. However, you still need to carry the backdestination URL across requests. Either via GET parameter, a session variable, or localstorage.

    Perhaps you could generalize the implementation by always storing the history of last X URLs. Then, if you need to modify the back destination, use some kind of algorithm to determine where users came from. E.g. take the user to the last URL where the script file name is not the current one:

    history of requests:

     /list.php
     /list.php?page=2
     /client.php?id=123     // User viewing the client
     /client.php?id=123     // Page reload after POST
    

    Now, if a user clicks back, the same client.php is loaded. However, you can create a generic script that modifies the History object with replaceState().

    I hope this gives you some ideas.