Created
March 22, 2024 12:32
-
-
Save bronwynv/5fdc57bb0773c796b3a7236ac563f925 to your computer and use it in GitHub Desktop.
Persist landing page query args during current session while browsing to other pages
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
<script> | |
// Function to parse query parameters from URL | |
function getQueryParams(url) { | |
const queryParams = {}; | |
const urlParams = new URLSearchParams(url.search.slice(1)); | |
for (const [key, value] of urlParams.entries()) { | |
queryParams[key] = value; | |
} | |
return queryParams; | |
} | |
// Function to store query parameters in session storage | |
function storeQueryParamsInSessionStorage(params) { | |
sessionStorage.setItem('queryParams', JSON.stringify(params)); | |
} | |
// Function to retrieve query parameters from session storage | |
function getQueryParamsFromSessionStorage() { | |
const storedParams = sessionStorage.getItem('queryParams'); | |
return storedParams ? JSON.parse(storedParams) : {}; | |
} | |
// On page load | |
window.addEventListener('load', function() { | |
const landingPageUrl = new URL(window.location.href); | |
const queryParams = getQueryParams(landingPageUrl); | |
// Store query parameters in session storage | |
storeQueryParamsInSessionStorage(queryParams); | |
}); | |
// Before navigating to other pages | |
document.addEventListener('click', function(event) { | |
const target = event.target; | |
if (target.tagName === 'A') { | |
const queryParams = getQueryParamsFromSessionStorage(); | |
if (Object.keys(queryParams).length > 0) { | |
const href = target.getAttribute('href'); | |
if (href && href.indexOf('?') !== -1) { | |
// URL already has query parameters, merge them with session storage parameters | |
const mergedParams = Object.assign({}, queryParams, getQueryParams(new URL(href))); | |
target.setAttribute('href', appendQueryParams(href, mergedParams)); | |
} else { | |
// Append session storage query parameters to the URL | |
target.setAttribute('href', appendQueryParams(href || '', queryParams)); | |
} | |
} | |
} | |
}); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment