-
-
Save geminorum/d113487085065920e1a4cc4596cb4d8f to your computer and use it in GitHub Desktop.
JavaScript one-liner for removing a ?message=... parameter from the visible URL in the browser
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
history.replaceState && history.replaceState( | |
null, '', location.pathname + location.search.replace(/[\?&]message=[^&]+/, '').replace(/^&/, '?') | |
); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment