So I have a form that I'm using that once the submission is successful, it adds a ?success
query string to the URL.
With the below code, whenever a user reaches the ?success
page, it will prevent them from hitting the back button which helps prevent submissions to the database - The issue is, if I have server sided errors, it will prevent the back button on the whole page until the cache is cleared.
function disableBack() {
window.history.forward()
}
window.onload = disableBack();
window.onpageshow = function(evt) {
if (evt.persisted)
evt.preventDefault();
disableBack()
};
How can I make the following javascript snippet fire off once the ?success
query string is present only? I've tried the following code but had no luck:
if (location.search === "?success") {
// Prevent the form from being resubmitted on backspace
function disableBack() {
window.history.forward()
}
window.onload = disableBack();
window.onpageshow = function(evt) {
if (evt.persisted)
evt.preventDefault();
disableBack()
};
}
Updated answer (It still redirects back):
function disableBack() {
window.history.forward()
}
var includesURLSearchString = searchString => location.search.includes(searchString);
var hasQueryString = includesURLSearchString('success');
console.log(hasQueryString);
if (hasQueryString) {
// Prevent the form from being resubmitted on backspace
window.onload = disableBack();
window.onpageshow = function (evt) {
if (evt.persisted)
evt.preventDefault();
disableBack()
};
}