Broken history for a self-updating form using post-redirect-get
Asked Answered
T

1

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
Terr answered 13/3, 2019 at 22:3 Comment(2)
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 ?Dunnage
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.Terr
D
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

Donegal answered 23/3, 2019 at 7:7 Comment(2)
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?Terr
You can find out by checking the HTTP status code for that page, it should be 30X for redirection.Donegal

© 2022 - 2024 — McMap. All rights reserved.