Looking for a site's URL information, then the window.location object is for you! Use its properties to get information on the current page address or use its methods to do some page redirect or refresh 💫
In my above example, you will notice that host and hostname returns the value. So why do these properties. Well, it has do with the port number. Let's take a look.
Not only can you call these location properties to retrieve the URL information. You can use it to set new properties and change the URL. Let's see what I mean.
// START 'www.samanthaming.com'
window.location.pathname = '/tidbits'; // Set the pathname
// RESULT 'www.samanthaming.com/tidbits'
Here's the complete list of properties that you can change:
// Example
window.location.protocol = 'https'
.host = 'localhost:8080'
.hostname = 'localhost'
.port = '8080'
.pathname = 'path'
.search = 'query string' // (you don't need to pass ?)
.hash = 'hash' // (you don't need to pass #)
.href = 'url'
The only property you can't set is window.location.origin. This property is read-only.
The window.location returns a Location object. Which gives you information about the current location of the page. But you can also access the Location object in several ways.
All 4 of these properties point at the same Location object. I personally prefer window.location and would actually avoid using location. Mainly because location reads more like a generic term and someone might accidentally name their variable that, which would override the global variable. Take for example:
// https://www.samanthaming.com
location.protocol; // 'https'
function localFile() {
const location = '/sam';
return location.protocol;
// ❌ undefined
// b/c local "location" has override the global variable
}
I think that most developer is aware that window is a global variable. So you're less likely to cause confusion. To be honest, I had no idea location was a global variable until I wrote this post 😅. So my recommendation is to be more explicit and use window.location instead 👍
Here's my personal order of preference:
// ✅
1. window.location // 🏆
2. document.location
// ❌
3. window.document.location // why not just use #1 or #2 😅
4. location // feels too ambiguous 😵
Of course, this is just my preference. You're the expert of your codebase, there is no best way, the best way is always the one that works best for you and your team 🤓
As to which to use, I couldn't find much information as to which is better; but if you do, please submit a PR on this 😊. But I did find a performance test on the difference.
One thing I want to note about these speed tests is that it is browser specific. Different browser and versions will render different outcome. I'm using Chrome, so the href came out faster then the rest. So that's one I'll use. Also I think it reads more explicit then toString(). It is very obvious that href will provide the URL whereas toString seems like something it being converted to a string 😅
Both of these methods will help you redirect or navigate to another URL. The difference is assign will save your current page in history, so your user can use the "back" button to navigate to it. Whereas with replace method, it doesn't save it. Confused? No problem, I was too. Let's walk through an example.
Assign
1. Open a new blank page
2. Go to www.samanthaming.com (current page)
3. Load new page 👉 `window.location.assign('https://www.w3schools.com')`
4. Press "Back"
5. Returns to 👉 www.samanthaming.com
Replace
1. Open a new blank place
2. Go to www.samanthaming.com (current Page)
3. Load new page 👉 `window.location.replace('https://www.w3schools.com')`
4. Press "Back"
5. Return to 👉 blank page
Current Page
I just need to emphasize the "current page" in the definition. It is the page right before you call assign or replace.
1. Open a new blank place
2. Go to www.developer.mozilla.org
3. Go to www.samanthaming.com 👈 this is the current Page
4. window.location.assign('https://www.w3schools.com'); // Will go to #3
4. window.location.replace('https://www.w3schools.com'); // Will go to #2
By now, you know we can change the properties of the window.location by assigning a value using =. Similarly, there are methods we can access to do some actions. So in regards to "how to redirect to another page", well there are 3 ways.
// Setting href properties
window.location.href = 'https://www.samanthaming.com';
// Using Assign
window.location.assign('https://www.samanthaming.com');
// Using Replace
window.location.replace('https://www.samanthaming.com');
All three does redirect, the difference has to do with browser history. href and assign are the same here. It will save your current page in history, whereas replace won't. So if you prefer creating an experience where the navigation can't press back to the originating page, then use replace 👍
So the question now is href vs assign. I guess this will come to personal preference. I like the assign better because it's a method so it feels like I'm performing some action. Also there's an added bonus of it being easier to test. I've been writing a lot of Jest tests, so by using a method, it makes it way easier to mock.
But for that that are rooting for href to do a page redirect. I found a performance test and running in my version of Chrome, it was faster. Again performance test ranges with browser and different versions, it may be faster now, but perhaps in future browsers, the places might be swapped.
Okay, a bit of a tangent and give you a glimpse of how this cheatsheet came to be. I was googling how to redirect to another page and encountered the window.location object. Sometimes I feel a developer is a journalist or detective - there's a lot of digging and combing through multiple sources for you to gather all the information available. Honestly, I was overwhelmed with the materials out there, they all covered different pieces, but I just wanted a single source. I couldn't find much, so I thought, I'll cover this in a tidbit cheatsheet! Scratch your own itch I always say 👍
@jam3sn_codes: This is awesome, I’ve used window.location.href in the past, but didn’t realise how simple it is to access sections of the URL!
If you want to see a live-action of what James is talking about, check out the table of content at the top of this article. Click on it and it will scroll down to the specific section of the page.
// 1. Add the hash identifier as an "id" to any element
<h2 id="top">Top Section</h2>
// 2. Pass that id name as the hash
<a href="https://samanthaming.com/#top">Back to top</a>
You’re buying a domain name, you probably already have some idea what it is. But many people are confused by terms like domain name, top level domain, third level domain, uniform resource locator and the like. If you’re one of these people, this article is for you. It will provide a clear understanding of what a domain name really is and how it fits into what you type into your Internet browser’s address bar.
The “.com” part is called the top level domain (TLD).
The following are some popular TLDs that you might find on the Internet:
.com: commercial
.org: non-profit organization
.gov: government
.net: network resources
.edu: education
.tv: country code top-level domain (ccTLD) for the islands of Tuvalu, but most often used for television
Now, the most important part is the part between the dots, “DomainSherpa.” The part is called domain.
Some rules for the domain are:
It does not allow spaces.
It is not case sensitive, “DomainSherpa” and “domainsherpa” will lead you to the same location.
You can have dashes or numbers, “domainsherpa-123” for example.
Spaces between characters are not allowed, nor are special characters such as !, @, #, $, %, ^, &, <, *, (, ), {, }, |, [, ], or >.
Domains can contain as many as 63 characters. If you include domain suffixes in your count it can be longer (+4 for .com and +6 for .co.uk, for example).
The domain along with the top level domain together form a domain name. This term is synonymous to “website address.”
However, there is one additional part that accompanies a domain name to complicate matters slightly. It is the part before the dot, specifically called sub-domain. In practice, however, a website can consist of many parts or area within the same location of a domain. The following website addresses illustrate:
mail.domainsherpa.com
blog.domainsherpa.com
stuff.domainsherpa.com
These sub-domains (mail, blog and stuff) are owned and operated by the same operator. The sub-domain allows visitors to channel their intention into different parts of a website.
Domain Names and the URL
The Uniform Resource Locator (URL) has significant role on the Internet because it will directs us to a specific website. The parts of a URL can be examined from the following example:
The group of letters “http” stands for Hyper Text Transfer Protocol and is prefix to identify the location of a domain the World Wide Web. Technically, the protocol is used to communicate with a web server when sending and fetching of a web. Additionally, you might also find https (Hyper Text Transfer Protocol Secure, or encrypted) as a protocol. It is used when you open a web page that requires you to disclose important information such as bank account, credit card number or personal details. Other protocols that are common include ftp (File Transfer Protocol) and smtp (Simple Mail Transfer Protocol).
2. Sub-Domain and Domain Name
The www.domainsherpa.com is called sub-domain (www) and domain name (domainsherpa). They are unique names that will identify a specific location on your website on the Internet.
3. Path
After the top level domain you can see “80” just after a colon. It is called port. The number 80 is used for the http and 443 is used for secure port. In addition, the listening-module is the path or directory in which specific data will be retrieved.
4. Query and Parameters
The part after the question mark (?) is called the query, which represents a dynamic request to a website and is typically generated from a database. On the other hand, 782468276383 is called the parameter or technically defined as small piece of information found in the query.
5. Fragment
The string of words and numbers 00h02m30s are called fragment. The fragment is a section contains in a web page.