DEV Community

loading...
Cover image for window.location Cheatsheet

window.location Cheatsheet

samanthaming profile image Samantha Ming Originally published at samanthaming.com ใƒปUpdated on ใƒป7 min read

Alt Text

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 ๐Ÿ’ซ

https://www.samanthaming.com/tidbits/?filter=JS#2

window.location.origin   โ†’ 'https://www.samanthaming.com'
               .protocol โ†’ 'https:'
               .host     โ†’ 'www.samanthaming.com'
               .hostname โ†’ 'www.samanthaming.com'
               .port     โ†’ ''
               .pathname โ†’ '/tidbits/'
               .search   โ†’ '?filter=JS'
               .hash     โ†’ '#2'
               .href     โ†’ 'https://www.samanthaming.com/tidbits/?filter=JS#2'
window.location.assign('url')
               .replace('url')
               .reload()
               .toString()

window.location Properties

window.location Returns
.origin Base URL (Protocol + hostname + port number)
.protocol Protocol Schema (http: or https)
.host Domain name + port
.hostname Domain name
.port Port Number
.pathname The initial '/' followed by the Path
.search ? followed by Query String
.hash # followed by the Anchor or Fragment identifier
.href Full URL

Difference between host vs hostname

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.

URL without Port

https://www.samanthaming.com

window.location.host; // 'www.samanthaming.com'
window.location.hostname; // 'www.samanthaming.com'

window.location.port; // ''

URL with Port

https://www.samanthaming.com:8080

window.location.host; // 'www.samanthaming.com:8080'
window.location.hostname; // 'www.samanthaming.com'

window.location.port; // '8080'

So host will include the port number, whereas hostname will only return the host name.

How to change URL properties

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.

Location Object

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.

window.location          โ†’ Location
window.document.location โ†’ Location
document.location        โ†’ Location
location                 โ†’ Location

The reason we can do this is because these are global variables in our browser.

Alt Text

window.location vs location

All 4 of these properties points 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 accidently 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 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 ๐Ÿค“

window.location Methods

window.location
.assign() Navigates to the given URL
.replace() Navigates to given URL & removes current page from the session history
.reload() Reload the current page
.toString() Returns the URL

window.location.toString

Here's the definition from MDN

This method returns the USVString of the URL. It is a read-only version of Location.href

In other words, you can use it to get the href value from the

// https://www.samanthaming.com

window.location.href; // https://www.samanthaming.com
window.location.toString(); // https://www.samanthaming.com

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.

JSPerf: Location toString vs Location href

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 ๐Ÿ˜…

assign vs replace

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

How to Do a Page Redirect

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');

replace vs assign vs href

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.

window.location.assign = jest.fn();

myUrlUpdateFunction();

expect(window.location.assign).toBeCalledWith('http://my.url');

Credit StackOverflow: @kieranroneill:

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.

JSPerf: href vs assign

Scratch your own itch ๐Ÿ‘

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 ๐Ÿ‘

Resources

Thanks for reading โค
Say Hello! Instagram | Twitter | SamanthaMing.com

Discussion

pic
Editor guide
Collapse
mirkan1 profile image
Mirkan

Great article but I found an error

on

Here's the complete list of properties that you can change:

// Example

window.location.protocol = 'https'
               .host     = 'localhost'
               .hostname = 'localhost:8080'
               .port     = '8080'
               .pathname = 'path'
               .search   = 'query string' // (you don't need to pass ?)
               .hash     = 'hash' // (you don't need to pass #)
               .href     = 'url'

.hostname and .host should be swaped

take care, Renas

Collapse
samanthaming profile image
Samantha Ming Author

AH yikes ๐Ÿ˜ฑ Let me fix that now!! Great catch! Thanks for letting me know ๐Ÿ˜ฐ

Collapse
mirkan1 profile image
Mirkan

Can you follow me back if posible?

Collapse
corentinbettiol profile image
Corentin Bettiol

Good to know. I think I'm starting to understand how dev.to work and why it is so fast (hover on link => make request and store result in cache, click on link = assign url and load cached content).

I may implement those tricks to enhance user experience on my websites :)

Collapse
samanthaming profile image
Samantha Ming Author

woooo, would love to see the inner working of how dev.to works ๐Ÿคฉ

Collapse
patarapolw profile image
Pacharapol Withayasakpunt

It's Preact. You can find source code on GitHub.

Collapse
andy profile image
Andy Zhao (he/him)

We use InstantClick for that "hover on link => make a request" effect :) instantclick.io/

Loading cached content is mostly because of Fastly!

Most of the pages are Rails pages, and there's some Preact mixed in every once in a while.

Collapse
corentinbettiol profile image
Corentin Bettiol

Don't really know how caching is managed or anything about the Rail framework, but instanclick seems to be a gold nugget!

Thanks for the link, and bravo for this insanely fast website :)

Collapse
myfonj profile image
Michal ฤŒaplygin

Heads up: root URLs always end with slash. More specifically, the path part that follows host and port is mandatory and according URL format specification cannot be blank nor omitted and must start with slash, so the shortest value usually denoting root path is just '/'. Most agents tend to fix invalid input and silently add missing parts of URL before making request, and some user agents tend to hide single slash of root paths for (dubiously) aesthetic reasons, but actual HTTP request such agent produces always involves / path. "URLs" like http://host, http://host?search, http://host#hash are all in fact invalid and should be expressed as http://host/, http://host/?search, http://host/#hash.

window.location.href;
// never yields 'https://www.samanthaming.com'
// but rather 'https://www.samanthaming.com/'

url.spec.whatwg.org/#concept-url-path
url.spec.whatwg.org/#path-absolute...

Collapse
ben profile image
Ben Halpern

This is fabulous

Collapse
samanthaming profile image
Samantha Ming Author

Thanks Ben! ๐Ÿ˜„

Collapse
5t3ph profile image
Stephanie Eckles

When I was trying to decide an efficient way to determine if files were being served on localhost or prod, I came here and ended up with if(window.location.port) to test for localhost ๐Ÿ™ŒI'm sure I will visit more in the future, great job creating an excellent, clear resource!

Collapse
samanthaming profile image
Samantha Ming Author

Nice! Glad you found the article helping and you were able to apply the knowledge right away! I also list all my tidbits on my site if you want another resource to check out ๐Ÿ˜Š > samanthaming.com/

Collapse
patarapolw profile image
Pacharapol Withayasakpunt

I often use new URL(location.href).searchParams, BTW. Much more powerful than location.search.

Collapse
samanthaming profile image
Samantha Ming Author

OH COOL! must be a new-ish web API, no support for IE ... hmm...did they create this to hopefully replace window.location ๐Ÿค”

I'll need to look into it, maybe for a future tidbit ๐Ÿ˜Š

Collapse
mirzaa profile image
Mirzaa

Wonderful, thanks for the breakdown :)

Collapse
samanthaming profile image
Samantha Ming Author

You're very welcome! Thanks for reading ๐Ÿ˜„

Collapse
victorekpodecodedigital profile image
Collapse
samanthaming profile image
Samantha Ming Author

Thank you! ๐Ÿ™‚

Collapse
chiubaca profile image
Alex Chiu

brilliant break down! really filled in the gaps for me. ๐Ÿ™Œ

Collapse
samanthaming profile image
Samantha Ming Author

awesome, glad to hear that! Thanks for reading my article ๐Ÿ˜Š

Collapse
mustapha profile image
Mustapha Aouas

This is a great Post!
I learned something thanks ๐Ÿ’ฏ

Collapse
samanthaming profile image
Samantha Ming Author

Thanks Mustapha! So glad this post was helpful for you ๐Ÿ‘

Collapse
wrldwzrd89 profile image
Eric Ahnell

You're so good at explaining this stuff to other developers, Samantha! I learned a bunch of things from reading.

Collapse
samanthaming profile image
Samantha Ming Author

Thank you Eric! Being able to explain and communicate where other people can understand is a skill I'm trying to get better at. So I'm glad to hear I'm doing okay ๐Ÿ˜† -- there's still more room for improvement! I'll keep practicing -- hopefully one day i can explain it where non-dev will also understand it and they will be encouraged to learn programming ๐Ÿ˜Š

Collapse
dotorimook profile image
dotorimook

Thanks for this well-organized post!

Collapse
lucianobarauna profile image
Luciano Baraรบna

Nice guide for a consultation

Collapse
andreisena profile image
Andrei Sena

Hi! Great article!

On the first example (samanthaming.com/tidbits/?filter=JS#2), window.location.href would return the entire URL.

Collapse
samanthaming profile image
Samantha Ming Author

ah yikes! great catch, let me fix it ๐Ÿ˜ฑ Thanks for letting me know ๐Ÿ˜จ

Collapse
jesuissuyaa profile image
๐ŸŸ

Thank you so much for taking your time and effort to write this article AND adding a beautiful infographic โ™ฅ๏ธ

Collapse
samanthaming profile image
Samantha Ming Author

Glad you enjoyed the image and article! that's a double success, thanks for the positive feedback ๐Ÿ˜Š