- DSA with JS - Self Paced
- JS A to Z Guide
- JS Operator
- JS Examples
- Free JS Course
- Explore Our Geeks Community
- Difference between proto and prototype
- Difference between console.dir and console.log
- What is the difference between async.waterfall and async.series?
- What is the difference between parseInt() and Number() ?
- Difference between interfaces and classes in TypeScript
- How to use array that include and check an object against a property of an object ?
- Difference between Function.prototype.apply and Function.prototype.call
- Differences between ES6 class and ES5 function constructors
- Difference between v-bind and v-model in Vue.js
- Difference between Object.values and Object.entries Methods
- How to use an HTTP GET or POST for Ajax Calls ?
- What’s the best way to reload / refresh an iframe?
Window.location is a property that returns a Location object with information about the document’s current location. This Location object represents the location (URL) of the object it is linked to i.e. holds all the information about the current document location (host, href, port, protocol, etc.)
All three commands are used to redirect the page to another page/website but differ in terms of their impact on the browser history.
window.location.href Property :
- The href property on the location object stores the URL of the current webpage.
- On changing the href property, a user can navigate to a new URL, i.e. go to a new webpage.
- It adds an item to the history list (so that when the user clicks the “Back” button, he/she can return to the current page).
- Updating the href property is considered to be faster than using the assign() function (as calling a function is slower than accessing the property).
Example: This example shows the use of the window.location.href property.
Note: The following 2 lines of code perform the same purpose.
window.location.replace Property :
- The replace function is used to navigate to a new URL without adding a new record to the history.
- As the name suggests, this function “replaces” the topmost entry from the history stack, i.e., removes the topmost entry from the history list, by overwriting it with a new entry.
- So, when the user clicks the “Back” button, he/she will not be able to return to the current page.
- Hence, the major difference between the assign() and replace() methods is that the replace() function will delete the current page from the session history.
- The replace function does not wipe out the entire page history, nor does it make the “Back” button non-functional.
Example: This example shows the use of the window.location.replace property.
window.location.assign Property :
- The assign function is similar to the href property as it is also used to navigate to a new URL.
- The assign method, however, does not show the current location, it is only used to go to a new location.
- Unlike the replace method, the assign method adds a new record to history (so that when the user clicks the “Back” button, he/she can return to the current page).
- However, rather than updating the href property, calling a function is considered safer and more readable.
- The assign() method is also preferred over href as it allows the user to mock the function and check the URL input parameters while testing.
Example: This example shows the use of the window.location.assign property.
Difference between window.location.replace, window.location.assign and window.location.href properties:
Please Login to comment...
- Web Technologies - Difference Between
- Difference Between
- Web Technologies
Please write us at [email protected] to report any issue with the above content
Improve your Coding Skills with Practice
- Skip to main content
- Skip to search
- Skip to select language
- Sign up for free
- English (US)
Location: replace() 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.
If the assignment can't happen because of a security violation, a DOMException of the SECURITY_ERROR type is thrown. This happens if the origin of the script calling the method is different from the origin of the page originally described by the Location object, mostly when the script is hosted on a different domain.
If the provided URL is not valid, a DOMException of the SYNTAX_ERROR type is thrown.
A string containing the URL of the page to navigate to.
None ( undefined ).
- The Location interface it belongs to.
- Similar methods: Location.assign() and Location.reload() .
C# Dot Net Programming tutorial & code examples
- React Native
We will see all differences in detail with examples.
The href property of the window.location object represents the complete URL of the current page. It can be both accessed and modified. When you assign a new URL to window.location.href , the browser will navigate to the specified location, triggering a full page refresh. Here’s an example:
This code will load the “https://codeindotnet.com” URL, replacing the current page with the new content and adding an entry to the browser history.
The replace method of the window.location object also allows you to navigate to a new URL, but with a crucial difference. When you invoke window.location.replace , the current page is immediately replaced with the new content, without creating a new entry in the browser history. This means that clicking the browser’s “Back” button will not take the user back to the previous page. Let’s see an example:
Upon executing this code, the browser will load “https://codeindotnet.com,” discarding the current page from the history.
The assign method of the window.location object is similar to window.location.href , as it navigates to a new URL and creates a new entry in the browser history. However, window.location.assign allows you to modify the current page’s URL without triggering a page refresh. Here’s an example:
This code will update the URL displayed in the address bar to “https://codeindotnet.com,” but the content of the page will remain unchanged. If you subsequently refresh the page or navigate to a different page, the new URL will appear in the browser history.
- window.location.href is used to navigate to a new URL, triggering a page refresh and creating a new entry in the browser history.
- window.location.replace replaces the current page with a new URL, without creating a history entry, making it impossible to go back to the previous page.
- window.location.assign modifies the current page’s URL without refreshing, allowing the creation of a new history entry.
Leave a Reply Cancel reply
Your email address will not be published. Required fields are marked *
- Remove underline from Hyperlink link – HTML, CSS
- Hide DataTables ‘Search and Pagination’
- How to Read Excel Cell Values using Open XML in C# .Net Core
- WordPress Custom Rest API – Adding Endpoints
- How to Create Custom Exception Filter in .Net Core C#?
The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.
The window.location object can be written without the window prefix.
- window.location.href returns the href (URL) of the current page
- window.location.hostname returns the domain name of the web host
- window.location.pathname returns the path and filename of the current page
- window.location.protocol returns the web protocol used (http: or https:)
- window.location.assign() loads a new document
Window Location Href
The window.location.href property returns the URL of the current page.
Display the href (URL) of the current page:
Window Location Hostname
The window.location.hostname property returns the name of the internet host (of the current page).
Display the name of the host:
Window Location Pathname
The window.location.pathname property returns the pathname of the current page.
Display the path name of the current URL:
Window Location Protocol
The window.location.protocol property returns the web protocol of the page.
Display the web protocol:
Window Location Port
The window.location.port property returns the number of the internet host port (of the current page).
Most browsers will not display default port numbers (80 for http and 443 for https)
Window Location Assign
The window.location.assign() method loads a new document.
Load a new document:
If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:
SheCodes Quick Links
- FREE Coding Class
- 💪 Monthly Challenges
- 👩💼 Success Stories
- 👩🎓 Graduates
- 🤖 Athena AI
- 🤝 SheCodes Connect
- 🌍 SheCodes Foundation
- Success stories
- Learn to Code
SheCodes Athena powered by AI
Your ai coding assistant, what do you need help with, window.location.href related coding questions, 👩💻 technical question.
🤔 Frequently Asked Questions
If you have any other questions, reach out to us at [email protected]
What is an AI Assistant?
AI stands for Artificial Intelligence. AI bots are able to learn from conversations with users and expand their knowledge this way.
SheCodes Athena will help you with technical questions about your code using artificial intelligence to find the answer. Imagine a super powerful human who has memorized everything on the internet and can access that knowledge in a matter of seconds. 🤯
SheCodes Athena can answer most coding-related questions, even complicated ones! It can even find bugs in your code and tell you how to fix them in just a few seconds. Impressive, right?
Just remember we're still in testing mode so the AI may return strange or incorrect replies. Feel free to message us if this happens!
What type of questions can I ask?
SheCodes Athena can only reply to coding-related technical questions. The same type of questions you would ask in the channels on Slack.
For questions that are not coding-related, write us here 😃
How do I ask a questions to the AI Assistant?
You should treat Athena like a SheCodes team member, so always be polite! 😊 Ask your questions as detailed as possible, just like you would do on Slack.
Here are some examples:
- Prettier isn't working on my VS Code. How do I fix this?
- How do I make bullet points with different colors using the list element?
- My code in Codesandbox is having some issues. Can you please tell me what the issue is? [Include the link to your Codesandbox]
Can I ask as many questions as I want?
For now, SheCodes Athena is limited to 5 questions per day for each student.
What if I have more questions?
In that case, you can either ask SheCodes Athena a follow-up question, or you can post on the designated weekly channel on Slack!
Our technical assistants are still available on Slack and are always happy to help! 😍💪
How can I post my code?
Remember, questions are limited to 1000 characters.
- If you're working with an HTML file : Post a snippet of your code related to the issue you're having (just copy the code and paste it into the question box).
- If you're working with Codesandbox : Good news, you can just post the link to your Codesandbox and the AI Assistant will be able to view your code.
- If you have a longer question that would require an entire HTML file or more than 1000 characters, post it in the designated weekly channels on Slack! 😃
Why the name Athena?
Athena was the Greek goddess of wisdom, among other elements. She received her name from the city of Athens, which she is known for protecting.
Much like the goddess Athena, SheCodes Athena is also incredibly wise and can solve complicated coding puzzles in a matter of seconds! 😍
Will AI replace developers?
Not likely. AI can automate tasks and make developers' jobs more efficient but it can't fully replace the human ability to deal with complex software. And AI will still require human developers to supervise and improve it further.
So developers may see their tasks change but they won't be replaced by AI. 👩💻🤝💻
- Understanding the window.location Object
The window.location object is a part of the window object and provides information about the current document’s URL. It also allows you to manipulate and navigate the browser’s history. The window.location object has several properties and methods that can be used to access and modify the current URL.
Properties of window.location
Let’s take a look at the properties of the window.location object and what information they provide:
- window.location.protocol : The protocol used by the current URL, such as http: or https: .
- window.location.host : The full domain and port of the current URL, such as codedamn.com:80 (where 80 is the default port number for HTTP).
- window.location.hostname : The domain name of the current URL, such as codedamn.com .
- window.location.port : The port number used by the current URL. If no port number is specified, this property will be an empty string.
- window.location.search : The query string of the current URL, including the leading question mark (?), such as ?id=123&name=John .
- window.location.hash : The URL fragment identifier, including the leading hash symbol (#), such as #section-1 .
Methods of window.location
The window.location object also provides several methods to manipulate and navigate the browser’s history:
- window.location.assign(url) : Loads a new document at the specified URL.
- window.location.replace(url) : Replaces the current document with a new one at the specified URL without adding an entry to the browser’s history.
- window.location.reload(forcedReload) : Reloads the current document. If the forcedReload parameter is set to true , the browser will bypass the cache and request the document from the server.
- Using window.location in Practice
Now that we’ve explored the properties and methods of the window.location object, let’s see how they can be used in practice.
Navigating to a New Page
To navigate to a new page, you can use the window.location.assign() method or simply set the window.location.href property to the desired URL. For example:
Both of these methods have the same effect: they load the specified URL in the current browser window.
Reloading the Current Page
To reload the current page, you can use the window.location.reload() method:
// Force a reload, bypassing the browser cache window . location . reload ( true ) ;
Replacing the Current Page
If you want to navigate to a new page without adding an entry to the browser’s history, you can use the window.location.replace() method:
This method is useful when you want to prevent users from using the back button to return to the previous page.
Working with Query Strings
To access and manipulate the query string of the current URL, you can use the window.location.search property. For example, you can retrieve the query string and parse its key-value pairs:
// Parse the query string into an object const queryParams = new URLSearchParams ( queryString ) ;
// Access the values of the query parameters const id = queryParams . get ( 'id' ) ; // '123' const name = queryParams . get ( 'name' ) ; // 'John'
Q: Can I use window.location to navigate to a different domain?
A: Yes, you can use window.location.assign() or set window.location.href to a URL from a different domain. However, due to the same-origin policy, you won’t be able to access or manipulate the content of the other domain’s pages.
Q: How can I get only the domain and protocol of the current URL?
A: You can concatenate the window.location.protocol and window.location.hostname properties to get the full domain and protocol of the current URL, like this:
Q: How can I change only the hash part of the current URL?
A: You can set the window.location.hash property to the desired value:
This will update the URL’s hash without reloading the page.
Q: What is the difference between window.location.assign() and window.location.replace()?
A: The window.location.assign() method loads a new URL and adds it to the browser’s history, allowing the user to navigate back to the previous page using the back button. The window.location.replace() method loads a new URL and replaces the current page in the browser’s history, preventing the user from navigating back to the previous page.
Unlimited access to all platform courses
100+ practice projects included
ChatGPT Based Instant AI Help
Structured Full-Stack Web Developer Roadmap To Get A Job
Exclusive community for events, workshops
Sharing is caring
Did you like what Mehul Mohan wrote? Thank them for their work by sharing it on social media.
No comment s so far
- Mastering SQL Window Functions: Analytical Solutio...
- Window Functions (ROW_NUMBER, RANK, DENSE_RANK, LE...
# window.location Cheatsheet
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 💫
- Difference between host vs hostname
- How to change URL properties
- window.location vs location
- assign vs replace
- replace vs assign vs href
- Scratch your own itch 👍
- Community Input
# window.location Properties
# 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
URL with Port
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.
Here's the complete list of properties that you can change:
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.
The reason we can do this is because these are global variables in our browser.
# 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:
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:
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
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
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.
I just need to emphasize the "current page" in the definition. It is the page right before you call assign or replace .
# 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.
# 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.
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
: 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.
- Share to Twitter Twitter
- Share to Facebook Facebook
- Share to LinkedIn LinkedIn
- Share to Reddit Reddit
- Share to Hacker News Hacker News
- Email Email
Console.table to display data, colorful console message, window.location cheatsheet, fresh tidbits.