Skip to content

Instantly share code, notes, and snippets.

@olets
Created June 25, 2021 23:54
Show Gist options
  • Save olets/de95e8d9dac0523b05ea2b6a8650c8ce to your computer and use it in GitHub Desktop.
Save olets/de95e8d9dac0523b05ea2b6a8650c8ce to your computer and use it in GitHub Desktop.
Redirect form submission without hash

When redirecting a form with a redirect input, for example

<input type="hidden" name="redirect" value="<url>">

the browser may preserve the window hash after the redirect. For example, submitting

<form>
  <input type="hidden" name="redirect" value="my-other-page">
  <button type="submit">
</form>

from mydomain.com/my-page#my-hash may take the user to mydomain.com/my-other-page#my-hash.

That isn't always desirable; for example it isn't uncommon to need to redirect to the top of another page, where a confirmation message may be shown. To do that, take the hash out of the current page before submitting the form:

myForm.addEventListener('submit', () => {
  window.history.pushState(null, '', window.location.pathname)
}

now submitting the above form from mydomain.com/my-page#my-hash should reliably take the user to mydomain.com/my-other-page.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment