Skip to content

Instantly share code, notes, and snippets.

@simonw
Last active May 15, 2025 20:37
Show Gist options
  • Select an option

  • Save simonw/9445b8c24ddfcbb856ec to your computer and use it in GitHub Desktop.

Select an option

Save simonw/9445b8c24ddfcbb856ec to your computer and use it in GitHub Desktop.

Revisions

  1. Simon Willison revised this gist Jan 22, 2016. 1 changed file with 1 addition and 1 deletion.
    2 changes: 1 addition & 1 deletion remove-message.js
    Original file line number Diff line number Diff line change
    @@ -1,3 +1,3 @@
    history.replaceState && history.replaceState(
    null, '', location.pathname + location.search.replace(/[\?&]message=[^&]+/, '')
    null, '', location.pathname + location.search.replace(/[\?&]message=[^&]+/, '').replace(/^&/, '?')
    );
  2. Simon Willison revised this gist Jan 22, 2016. 1 changed file with 3 additions and 1 deletion.
    4 changes: 3 additions & 1 deletion remove-message.js
    Original file line number Diff line number Diff line change
    @@ -1 +1,3 @@
    history.replaceState && history.replaceState(null, '', location.pathname + location.search.replace(/[\?&]message=[^&]+/, ''));
    history.replaceState && history.replaceState(
    null, '', location.pathname + location.search.replace(/[\?&]message=[^&]+/, '')
    );
  3. Simon Willison created this gist Jan 22, 2016.
    1 change: 1 addition & 0 deletions remove-message.js
    Original file line number Diff line number Diff line change
    @@ -0,0 +1 @@
    history.replaceState && history.replaceState(null, '', location.pathname + location.search.replace(/[\?&]message=[^&]+/, ''));
    23 changes: 23 additions & 0 deletions why-do-this.txt
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,23 @@
    When a form is submitted, best practice is to use redirect-after-post - you
    POST to a specific URL, that URL performs an action and then HTTP redirects
    the user to a confirmation page.

    This helps avoid unexpected behaviour with the browser reload and back
    buttons.

    Using this technique does have one downside: since you have redirected away
    from the page that performed the action, how do you know what kind of
    confirmation message to display to the user?

    There are two common ways of handing this:

    1. Using a "flash message" in a temporary cookie. This works well, but can
    behave strangely when multiple tabs are involved.
    2. Adding a ?message=MESSAGE-IDENTIFIER parameter to the redirect URL.
    This is reliable, but ugly. We don't want users to bookmark these URLs
    or share them with each other, as that will cause an incorrect message
    to be displayed.

    This JavaScript one-liner uses the HTML5 history API to improve the second
    approach, by removing the extra querystring paramater from the URL once the
    page has loaded, without causing the browser to reload the page.