Created
November 2, 2020 15:29
-
-
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
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
/** | |
* 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®ulator=regulatorValue" | |
* onclick="parseUrlAndInjectToCtaUrl(event)">Register here</a> | |
* | |
* Browser will redirect to http://foobar.com/?foobar=fromQuery®ulator=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