Last active
October 23, 2020 09:17
-
-
Save cahva/6e6565bfc3fb33ecbeb3b63f8ea29d8d to your computer and use it in GitHub Desktop.
Add current querystring to links
This file contains hidden or 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> | |
/** | |
* To add this to links in the page, add data variable data-inject-qs to the link. | |
* For example: | |
* <a href="https://google.fi" data-inject-qs>Google</a> | |
* | |
* And If current url is /something?hello=world, it will inject ?hello=world to that link | |
* It will became https://google.fi?hello=world | |
* | |
**/ | |
function tryEl(e) { | |
var injectableEl = document.querySelector('a[data-inject-qs]'); | |
if (!injectableEl) { | |
window.requestAnimationFrame(tryEl); | |
} else { | |
var currentSearchParams = window.location.search; | |
if (currentSearchParams.length > 0) { | |
var injecturls = document.querySelectorAll("a[data-inject-qs]"); | |
injecturls.forEach(function(node) { | |
if (node.href.indexOf(currentSearchParams) === -1) { | |
node.setAttribute('href', node.href + currentSearchParams); | |
} | |
}); | |
} | |
} | |
} | |
tryEl(); | |
</script> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Removed