Have you ever noticed how when you google something, the url of the page stores your search in a string?
https://www.google.com/
now searching for hello world!:
https://www.google.com/search?q=hello+world!...
Those are called query parameters. Their primary purpose is to tell the search engine what to search for. The benefit of them is the fact that the values are stored in the URL itself, meaning you can just copy the link to make the app search for the same thing again.
A query parameter link consists of:
?
- indicating the start of query parametersname=value
, separated by &
So for https://neocities.org/browse?sort_by=random&tag=blog
, the parameters are:
sort_by = random
tag = blog
Which tells the neocities search engine to look for random pages with the tag blog, of course.
We can't really search for stuff like this in neocities pages, but doesn't mean we can't use them in the way they weren't meant to be used.
Conveniently for us, JavaScript allows you to check the query parameters and do with them whatever we want.
It's very simple: window.location.search
gives us the string with your url that starts with "?".
To make it even simpler, there is an UrlSearchParams
class that has methods for getting the values out easily.
You can instantiate it with new UrlSearchParams(anyStringWithQueryParameters)
, which is usually the previously mentioned window.location.search
.
Example usage:
const params = new URLSearchParams(window.location.search);
if(params.has("name")) {
let userName = params.get("name") // getting out the value of parameter "name"
}
for (const [key, value] of params) { // looping through every parameter and its value
alert(key + " is " + value + "!");
}
You can use it for some wacky stuff, for example, this page should respond to parameter "name".
Try it yourself! Just add ?name=yourName
to the end of this URL and check the message :)
TODO: Talk about forms. Gotta go to sleep, cya!