Skip to content

Instantly share code, notes, and snippets.

@gkalmoukis
Created June 25, 2021 11:34
Show Gist options
  • Save gkalmoukis/b46537f42332f1f9888312c155a37ba3 to your computer and use it in GitHub Desktop.
Save gkalmoukis/b46537f42332f1f9888312c155a37ba3 to your computer and use it in GitHub Desktop.
Simpe script that allows you to keep all query parameters from URL
function setParameter(key, value) {
if (history.pushState) {
let parameters = new URLSearchParams(window.location.search);
parameters.set(key, value);
let newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + parameters.toString();
window.history.pushState({
path: newUrl
}, '', newUrl);
}
}
function unsetParameter(key) {
if (history.pushState) {
let parameters = new URLSearchParams(window.location.search);
parameters.delete(key);
let newUrl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + parameters.toString();
window.history.pushState({
path: newUrl
}, '', newUrl);
}
}
function getParameter(key) {
if (history.pushState) {
let parameters = new URLSearchParams(window.location.search);
return parameters.get(key);
}
}
function requestData(existingParameters) {
let newData = {};
if ('' !== $('#input').val().trim()) {
newParameters.input = $('#input').val().trim();
setGetParam('input', newParameters.input);
} else {
unsetGetParam('input');
}
return newParameters;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment