8

I have a URL /books, which lists some books, and a URL pattern /books/{some-book-title} which shows a view/update form for the metadata of a book. Here's a typical user story, where a user corrects an incorrect author entry:

GET /books

  <a href="/books/ulysses">Ulysses</a>
  <a href="/books/don-quixote">Don Quixote</a>

GET /books/ulysses

  <form action="/books/ulysses" method="post" enctype="application/x-www-form-urlencoded">
    <input name="author" value="Jamessss Joycessss">
  </form>

POST /books/ulysses FORMDATA author=James+Joyce

  Redirect 303 SEE OTHER location = /books/ulysses

GET /books/ulysses

  <form action="/books/ulysses" method="post" enctype="application/x-www-form-urlencoded">
    <input name="author" value="James Joyce">
  </form>

The problem is that the history stack is now

  • /books
  • /books/ulysses
  • /books/ulysses

so that when the user presses "back", they don't go back to /books, they just refresh the current page. Is there a non-javascript way to handle the update case so that the back button has the expected behavior? And if not, what's the javascript way to fix this?

EDIT: even more confusing if you post multiple times

GET /books
GET /books/ulysses    author=Jamesss Joycesss
POST author=3  ->  redirect shows author=3
POST author=2  ->  redirect shows author=2
POST author=1  ->  redirect shows author=1
Press back button /books/ulysses shows author=1
Press back button /books/ulysses shows author=2  (!!!)
Press back button /books/ulysses shows author=3  (!!!)
Press back button /books
Ned Twigg
  • 2,009
  • 2
  • 19
  • 37
  • Don't know what framework or system are you using, but can you just simply return the same response from the POST than the get avoiding the redirect ? – jgoday Mar 22 '19 at 23:56
  • 1
    I'm using the post-redirect-get pattern on purpose. When users press the back button, I don't want Chrome to give them the "resubmit data" dialog, and post-redirect-get accomplishes that much. – Ned Twigg Mar 23 '19 at 03:30

1 Answers1

0

A JavaScript way of modifying behavior of back button would be to use the history API

Here is a quick way to go to first page in the history stack. Just add an Event listener for back button and use history API.

window.history.go(0);

Have a look at the API : https://developer.mozilla.org/en-US/docs/Web/API/History_API

Divvya Mehta
  • 374
  • 1
  • 8
  • But I would only want this behavior in cases where I have been redirected to the same page. Is there a way to know if I was just redirected to the same page? – Ned Twigg Mar 24 '19 at 02:03
  • You can find out by checking the HTTP status code for that page, it should be 30X for redirection. – Divvya Mehta Mar 24 '19 at 12:45