Skip to content

Instantly share code, notes, and snippets.

@pgchamberlin
Created November 27, 2019 18:04
Show Gist options
  • Save pgchamberlin/db48381373bfe152293e141bec83679e to your computer and use it in GitHub Desktop.
Save pgchamberlin/db48381373bfe152293e141bec83679e to your computer and use it in GitHub Desktop.
Url params in JS
<!doctype html>
<html>
<head></head>
<body>
<a id="link">Link to change</a>
<script type="text/javascript">
(() => {
const params = new URLSearchParams(window.location.search)
const name = params.get("name")
let link = document.getElementById("link")
link.href = `./page2.html?name=${name}`
link.innerHTML = `Click here ${name}`
})()
</script>
</body>
</html>
<!doctype html>
<html>
<head></head>
<body>
<p id="replace">Replace this with greeting</p>
<script type="text/javascript">
(() => {
const params = new URLSearchParams(window.location.search)
const name = params.get("name")
let replace = document.getElementById("replace")
replace.innerHTML = `Hello ${name}`
})()
</script>
</body>
</html>

Read URL params in JS and modify links based on them

This Gist contains the source for two HTML pages. The first page, page1.html takes a request with a query param name and templates that into a link to the second page, page2.html.

To test this youself save those pages in the same folder somewhere on your computer, than open page1.html in a web browser. Modify the link in the URL bar to contain the query param name with some value, i.e.:

file:///Users/myusername/some_directory/page1.html?name=Derek

The page should rewrite itself to contain a link to:

file:///Users/myusername/some_directory/page2.html?name=Derek

This page should say "Hello Derek". Hopefully.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment