I have a simple task! I want that when I submit a form and get success or error message of the form, I go to the form directly ( using anchors ), so in order to do so, I added a parametr in my from action's URL, like that :
action="%%url%%?form-submitted=true"
And when the form is submitted I wrote this code :
// This script is for moving the page to the form is the page is loaded by submitting the form
let pageUrl = window.location.href;
let url = new URL(pageUrl);
let formSubmitted = url.searchParams.get("form-submitted");
if(formSubmitted){
window.location.href = "#form-container";
}
The code is working perfectly fine, I am moving to my form when submitting the form, but if I scroll in the page and go check the slideshow for example, and I decide to refresh the page, the form-submitted parameter is in the URL, so when refreshing I go again to the form, which is not pleasant.
In order to fix that, I have to remove the query parameter from the URL without refreshing the page, I tried this:
// This script is for moving the page to the form is the page is loaded by submitting the form
let pageUrl = window.location.href;
let url = new URL(pageUrl);
let formSubmitted = url.searchParams.get("form-submitted");
history.pushstate({}, null, '');
if(formSubmitted){
window.location.href = "#form-container";
}
I was excepting that to keep just my domain plus the anchor tag, but it seems like nothing is happening.
Try adding the origin url and path only to your
url
param forhistory.pushState
:With history, you can also just use a relative url:
See also URL Constructor (which you are using already in your example).
The reason your original code did not work is that
url
inhistory.pushState()
is optional, and an empty string''
is falsy. So in your case, since this parameter was not specified with a truthy value, it was set to the document's current URL.