skip to Main Content

I have a back button on my pages which uses the browsers history api. Call this page, page b

 <a href="javascript:void(0)" onclick="history.go(-1)" class="btn btn-default pull-left" style="margin-right:10px;">Back</a>

This works great and takes me to the previous page. We need this functionaility as there are many different paths to end up on this page and storing all the different URL params from previous pages would not be possible.

The problem i have is the page (B), has many forms. When these forms are submited, the page is refreshed. This then adds to the history meaning users must now press back multiple times to get back to the previous page. As there are many different actions on page (B), the user could technically submit 5 or 6 forms. This would mean it would take 5 or 6 clicks to actually go back to the previous page.

Is there any way to ignore pages refreshes on my current page whilst storing the previous page? I would be useful if this could be done with URL’s and ignoring any extra params in the url. so just taking the pagename.php for example and nothing there after.

Is there any other suggestions as to how I might fix this behaviour?

I have tried using pushState or popstate, I have also tried using window.reload or opening in a new tab but this doesnt work as expected. We used to use PHP sessions to store previous page url’s. This worked great but doesnt work when using multiple tabs.

If this is not possible what would be the suggestion here? There are many different URL’s that all lead to this page. Each of those URL’s have their own required url parameters.

2

Answers


  1. Chosen as BEST ANSWER

    So Ive got it.

    Page (A) which is a potential of 5 or 6 different pages you create the following code;

      localStorage.setItem('customHomePage', window.location.href);
    

    on page (B) create the following code

        function goBack()
        {
            var previousPage = localStorage.getItem('customHomePage');
            if (previousPage)
                window.location.href = previousPage;
        }
    

    now it doesn't matter how many times page (B) is reloaded and for what ever reason. Instead it will always go back to the page that sent you here. You have to remember to put this on all pages that send you to this page


  2. Use replaceState

    use replaceState instead of pushState to add new entries to the history, you can use the replaceState method to modify the current entry.

    history.replaceState(null, '', window.location.href);
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search