window.location Cheatsheet | SamanthaMing.com (2022)

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
    • Difference between host vs hostname
    • How to change URL properties
  • Location Object
    • window.location vs location
  • window.location Methods
    • window.location.toString
    • assign vs replace
  • How to Do a Page Redirect
    • replace vs assign vs href
  • Scratch your own itch 👍
  • Community Input
  • Resources

# 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

(Video) How to remember fields of window.location object?

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:

// Examplewindow.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 → Locationwindow.document.location → Locationdocument.location → Locationlocation → Location

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

window.location Cheatsheet | SamanthaMing.com (1)

(Video) Introduction to Windows Forensics

# window.location vs location

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.comlocation.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 🤓

# 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.comwindow.location.href; // https://www.samanthaming.comwindow.location.toString(); // https://www.samanthaming.com
(Video) Speed Up Windows 10 in 2020

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 page2. 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 place2. 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 place2. Go to www.developer.mozilla.org3. Go to www.samanthaming.com 👈 this is the current Page
(Video) I made the greatest tool ever! | tmux & cht.sh & fzf
4. window.location.assign('https://www.w3schools.com'); // Will go to #34. 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 propertieswindow.location.href = 'https://www.samanthaming.com';// Using Assignwindow.location.assign('https://www.samanthaming.com');// Using Replacewindow.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 👍

# Community Input

@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!

(Video) The Best Tool for Windows 10 | PowerToys

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<h1 id="top">Top Section</h1>// 2. Pass that id name as the hash<a href="https://samanthaming.com/#top">Back to top</a>

# Resources

FAQs

What is the difference between window location and document location? ›

The window. location is read/write on all compliant browsers. The document. location is read-only in Internet Explorer but read/write in Firefox, SeaMonkey that are Gecko-based browsers.

What does setting window location do? ›

The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.

How do I change the URL of a Windows location? ›

location = "https://www.example.com"; // Sets the new href (URL) for the current window. window. location. href = "https://www.example.com"; // Assigns a new URL to the current window.

What is the difference between window location and location href? ›

The href property on the location object stores the URL of the current webpage.
...
window.location.hrefwindow.location.replacewindow.location.assign
It is faster than using the assign().It is used when the current webpage needs to be removed from the history list.It is safer and more readable than using href.
4 more rows
30 Jun 2021

What will happen if you reference document location from within an object? ›

If you reference document. location from within an object, the interpreter will need to go from the function that references the variable, up out of the namespace to the global window scope, down to the document scope, and gets the location value.

What is window location pathname? ›

pathname. The pathname property of the Location interface is a string containing the path of the URL for the location. If there is no path, pathname will be empty: otherwise, pathname contains an initial '/' followed by the path of the URL, not including the query string or fragment.

What does window location Origin return? ›

Definition and Usage

The origin property returns the protocol, hostname and port number of a URL.

Is it safe to use window location href? ›

The first one, using the value, can be considered safe. The value of location. href is nothing more than a string. Of course it's part of user input, so you don't want to pass it to an eval statement, but that's true for all other forms of user input as well.

How do I change my location? ›

Add, change, or delete a location
  1. On your Android phone or tablet, say "Hey Google, open Assistant settings." Or, go to Assistant settings.
  2. Tap You. Your places.
  3. Add, change, or delete an address.

Does window location href work in mobile? ›

location. href and click() methods doesn't work on mobile phone. Bookmark this question.

How do I find my current Windows URL? ›

Answer: Use the window. location. href Property

You can use the JavaScript window. location. href property to get the entire URL of the current page which includes host name, query string, fragment identifier, etc.

What is the name of the Windows location that stores cut or copied information? ›

The Office Clipboard stores text and graphics that you copy or cut from anywhere, and it lets you paste the stored items into any other Office file.

Why is the location replace () method preferred over the location assign () method? ›

The replace() method of the Location interface replaces the current resource with the one at the provided URL. The difference from the assign() method is that after using replace() the current page will not be saved in session History , meaning the user won't be able to use the back button to navigate to it.

How does window location href work? ›

window. location. href is not a method, it's a property that will tell you the current URL location of the browser. Changing the value of the property will redirect the page.

How does location href work? ›

The Location href property in HTML is used to set or return the complete URL of the current page. The Location href property can also be used to set the href value point to another website or point to an email address.

What is a document location? ›

The Document. location read-only property returns a Location object, which contains information about the URL of the document and provides methods for changing that URL and loading another URL. Though Document. location is a read-only Location object, you can also assign a string to it.

What does document location href do? ›

The Location href property in HTML is used to set or return the complete URL of the current page. The Location href property can also be used to set the href value point to another website or point to an email address.

Is Windows location href safe? ›

The first one, using the value, can be considered safe. The value of location. href is nothing more than a string. Of course it's part of user input, so you don't want to pass it to an eval statement, but that's true for all other forms of user input as well.

How do I add document location to Quick Access Toolbar? ›

Click on the small options icon to the right of the quick access toolbar.
...
How To Show The Workbook Location In The Quick Access Toolbar
  1. Under the Choose commands from section, select Commands Not in the Ribbon.
  2. In the box below, scroll down until you see the Document Location and select it.
  3. Press the Add button.

Videos

1. DOM-Based Cross-Site Scripting (DOM XSS) Explained
(Andrew Hoffman)
2. HOW TO CHEAT ON AN ONLINE PROCTORED EXAM!! 😏🤫🔥 2022
(ThatOneMohamed)
3. 🚗 How to use Microsoft PowerToys
(Kevin Stratvert)
4. Final Fantasy 15 COMRADES - CHEAT SHEET - All Items & Weapon Locations PLUS Mission Names!
(FuzzfingerGaming)
5. 15 CMD Commands Every Windows User Should Know
(MUO)
6. 15 Useful PowerShell Commands for Beginners | Learn Microsoft PowerShell
(WindowsChimp)

Top Articles

You might also like

Latest Posts

Article information

Author: Ray Christiansen

Last Updated: 10/26/2022

Views: 6774

Rating: 4.9 / 5 (69 voted)

Reviews: 92% of readers found this page helpful

Author information

Name: Ray Christiansen

Birthday: 1998-05-04

Address: Apt. 814 34339 Sauer Islands, Hirtheville, GA 02446-8771

Phone: +337636892828

Job: Lead Hospitality Designer

Hobby: Urban exploration, Tai chi, Lockpicking, Fashion, Gunsmithing, Pottery, Geocaching

Introduction: My name is Ray Christiansen, I am a fair, good, cute, gentle, vast, glamorous, excited person who loves writing and wants to share my knowledge and understanding with you.