Skip to content

Instantly share code, notes, and snippets.

@flangofas
Created November 2, 2020 15:29
Show Gist options
  • Save flangofas/0c8b2df0786d9fbce4bf040ea777ccd4 to your computer and use it in GitHub Desktop.
Save flangofas/0c8b2df0786d9fbce4bf040ea777ccd4 to your computer and use it in GitHub Desktop.
Parses current URL and uses the query parameters to replace them on an existing URL
/**
* Parses current URL and uses the query parameters to
* replace them on an existing URL of a CTA in the document.
*
* For example,
* Current URL is: http://localhost:8000/?foobar=fromQuery#
* <a
* href="#"
* data-url="http://foobar.com/?foobar=foobarValue&regulator=regulatorValue"
* onclick="parseUrlAndInjectToCtaUrl(event)">Register here</a>
*
* Browser will redirect to http://foobar.com/?foobar=fromQuery&regulator=regulatorValue
*
* @param e
*/
function parseUrlAndInjectToCtaUrl(e) {
let el = e.target
let urlToParse = el.getAttribute('data-url')
const targetUrl = new URL(urlToParse)
let currentUrl = new URL(document.location.href)
targetUrl.searchParams.forEach((value, key) => {
let currentValue = currentUrl.searchParams.get(key)
if (!currentValue) {
return;
}
targetUrl.searchParams.set(key, currentValue)
})
window.location.href = targetUrl.toString()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment