Browser navigation: A Guide to window.location and window.history in JavaScript

The window.location and window.history objects in JavaScript are used for manipulating the URL and browser history respectively. While they are related, they serve different purposes and should be used based on the specific requirements of your application. In this guide, we’ll explore the differences between these objects and provide guidance on when to use each of them.

window.location

The window.location object represents the URL of the current page and provides methods for manipulating the URL. Here are some of the methods and properties provided by the window.location object:

  • window.location.href: Returns the entire URL of the current page, including the protocol, domain, path, query parameters, and fragment identifier. You can also set this property to change the current URL.
  • window.location.protocol: Returns the protocol (e.g., “http:” or “https:”) of the current page. You can also set this property to switch between HTTP and HTTPS protocols.
  • window.location.hostname: Returns the hostname (e.g., “example.com”) of the current page. You can also set this property to change the hostname.
  • window.location.pathname: Returns the path (e.g., “/path/to/page.html”) of the current page. You can also set this property to change the path.
  • window.location.search: Returns the query parameters (e.g., “?key1=value1&key2=value2”) of the current page. You can also set this property to change the query parameters.
  • window.location.hash: Returns the fragment identifier (e.g., “#section1”) of the current page. You can also set this property to change the fragment identifier.

You can also use the window.location.assign() and window.location.replace() methods to change the URL of the current page. The assign() method loads a new document and replaces the current document in the session history, while the replace() method replaces the current document without creating a new entry in the session history.

window.history

The window.history object provides methods for manipulating the browser history. Here are some of the methods provided by the window.history object:

  • window.history.back(): Loads the previous page in the browser history.
  • window.history.forward(): Loads the next page in the browser history (will only work if a next page exists in your history list).
  • window.history.go(n): Loads the page that is n steps away from the current page in the browser history. A positive value for n loads a page in the forward direction, while a negative value loads a page in the backward direction.

You can also use the window.history.pushState() and window.history.replaceState() methods to add or modify entries in the browser history without triggering a page reload. The pushState() method adds a new entry to the history stack, while the replaceState() method replaces the current entry.

When to use window.location vs window.history

Here are some guidelines on when to use window.location vs window.history in your application:

  • Use window.location to manipulate the URL of the current page. For example, you can use it to change the path, query parameters, or fragment identifier of the URL.
  • Use window.history to manipulate the browser history. For example, you can use it to navigate to a previous page or add a new entry to the history stack.
  • If you need to change the URL of the current page without reloading it, use the pushState() or replaceState() method of window.history. This is useful for building single-page applications or implementing client-side routing.
  • If you need to reload the current page or load a new page, use the assign() or replace() method of window.location. This is useful for navigating to a new URL and triggering a full page reload.
  • Be careful when using the replaceState() method of window.history, as it replaces the current entry in the history stack without creating a new entry. This means that if the user clicks the back button after using replaceState(), they will not be able to return to the previous page.
  • If you need to preserve the browser history when navigating within your application, you can use a client-side router library like React Router or Vue Router. These libraries provide a declarative way to define your application’s routes and handle navigation between them.
  • Keep in mind that changing the URL or browser history can affect the user’s browsing experience and potentially break existing bookmarks or links. Make sure to test your application thoroughly and provide appropriate feedback to the user when navigating between pages or changing the URL.

Real-world example

Imagine, you develop a common sidebar for different UIs. And there are several links and you need to optimize their behavior. Right now it is just a <a> tag with href attribute. And after clicking on the link it always reloads the full page and downloads all bundles and files.

Here is an example of how you can create a link element using HTML and JavaScript that looks at the link’s href and compares it with the current page location. If the hostname is the same, it uses the history API to navigate to the new page, otherwise, it continues with the default behavior.

HTML:

<a href="<https://www.example.com/page>" class="my-link">Link to Example Page</a>

JavaScript:

// Get all links with class "my-link"
const links = document.querySelectorAll('.my-link');

// Loop through each link
links.forEach(link => {
// Add an event listener for when the link is clicked
link.addEventListener('click', function(event) {
// Prevent the default behavior of the link
event.preventDefault();
// Get the href of the link
const href = this.getAttribute('href');
// Compare the hostname of the link with the current page location
if (window.location.hostname === new URL(href).hostname) {
// Use the history API to navigate to the new page
history.pushState(null, null, href);
} else {
// Continue with the default behavior
window.location.href = href;
}
});
});

In this example, we use querySelectorAll() to get all links with the class “my-link”, and then loop through each link using forEach(). For each link, we add an event listener for when the link is clicked. Inside the event listener, we prevent the default behavior of the link using preventDefault(), and then get the href attribute of the link using getAttribute(). We then use new URL() to create a new URL object from the href, and compare the hostname of the link with the hostname of the current page location using window.location.hostname. If the hostnames match, we use the history.pushState() method to navigate to the new page without reloading the page. If the hostnames do not match, we continue with the default behavior and navigate to the new page using window.location.href.

Conclusion

In this guide, we’ve explored the differences between window.location and window.history in JavaScript and provided guidance on when to use each of them. Remember to use window.location to manipulate the URL of the current page and window.history to manipulate the browser history. If you need to change the URL without reloading the page, use pushState() or replaceState(), and if you need to reload the page or load a new page, use assign() or replace(). Be mindful of the potential impact on the user’s browsing experience and use client-side router libraries to manage application navigation.

Level Up Coding

Thanks for being a part of our community! Before you go:

🚀👉 Join the Level Up talent collective and find an amazing job


Browser navigation: A Guide to window.location and window.history in JavaScript was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Aleksandr Guzenko

The window.location and window.history objects in JavaScript are used for manipulating the URL and browser history respectively. While they are related, they serve different purposes and should be used based on the specific requirements of your application. In this guide, we’ll explore the differences between these objects and provide guidance on when to use each of them.

window.location

The window.location object represents the URL of the current page and provides methods for manipulating the URL. Here are some of the methods and properties provided by the window.location object:

  • window.location.href: Returns the entire URL of the current page, including the protocol, domain, path, query parameters, and fragment identifier. You can also set this property to change the current URL.
  • window.location.protocol: Returns the protocol (e.g., “http:” or “https:”) of the current page. You can also set this property to switch between HTTP and HTTPS protocols.
  • window.location.hostname: Returns the hostname (e.g., “example.com”) of the current page. You can also set this property to change the hostname.
  • window.location.pathname: Returns the path (e.g., “/path/to/page.html”) of the current page. You can also set this property to change the path.
  • window.location.search: Returns the query parameters (e.g., “?key1=value1&key2=value2”) of the current page. You can also set this property to change the query parameters.
  • window.location.hash: Returns the fragment identifier (e.g., “#section1”) of the current page. You can also set this property to change the fragment identifier.

You can also use the window.location.assign() and window.location.replace() methods to change the URL of the current page. The assign() method loads a new document and replaces the current document in the session history, while the replace() method replaces the current document without creating a new entry in the session history.

window.history

The window.history object provides methods for manipulating the browser history. Here are some of the methods provided by the window.history object:

  • window.history.back(): Loads the previous page in the browser history.
  • window.history.forward(): Loads the next page in the browser history (will only work if a next page exists in your history list).
  • window.history.go(n): Loads the page that is n steps away from the current page in the browser history. A positive value for n loads a page in the forward direction, while a negative value loads a page in the backward direction.

You can also use the window.history.pushState() and window.history.replaceState() methods to add or modify entries in the browser history without triggering a page reload. The pushState() method adds a new entry to the history stack, while the replaceState() method replaces the current entry.

When to use window.location vs window.history

Here are some guidelines on when to use window.location vs window.history in your application:

  • Use window.location to manipulate the URL of the current page. For example, you can use it to change the path, query parameters, or fragment identifier of the URL.
  • Use window.history to manipulate the browser history. For example, you can use it to navigate to a previous page or add a new entry to the history stack.
  • If you need to change the URL of the current page without reloading it, use the pushState() or replaceState() method of window.history. This is useful for building single-page applications or implementing client-side routing.
  • If you need to reload the current page or load a new page, use the assign() or replace() method of window.location. This is useful for navigating to a new URL and triggering a full page reload.
  • Be careful when using the replaceState() method of window.history, as it replaces the current entry in the history stack without creating a new entry. This means that if the user clicks the back button after using replaceState(), they will not be able to return to the previous page.
  • If you need to preserve the browser history when navigating within your application, you can use a client-side router library like React Router or Vue Router. These libraries provide a declarative way to define your application’s routes and handle navigation between them.
  • Keep in mind that changing the URL or browser history can affect the user’s browsing experience and potentially break existing bookmarks or links. Make sure to test your application thoroughly and provide appropriate feedback to the user when navigating between pages or changing the URL.

Real-world example

Imagine, you develop a common sidebar for different UIs. And there are several links and you need to optimize their behavior. Right now it is just a <a> tag with href attribute. And after clicking on the link it always reloads the full page and downloads all bundles and files.

Here is an example of how you can create a link element using HTML and JavaScript that looks at the link’s href and compares it with the current page location. If the hostname is the same, it uses the history API to navigate to the new page, otherwise, it continues with the default behavior.

HTML:

<a href="<https://www.example.com/page>" class="my-link">Link to Example Page</a>

JavaScript:

// Get all links with class "my-link"
const links = document.querySelectorAll('.my-link');

// Loop through each link
links.forEach(link => {
// Add an event listener for when the link is clicked
link.addEventListener('click', function(event) {
// Prevent the default behavior of the link
event.preventDefault();
// Get the href of the link
const href = this.getAttribute('href');
// Compare the hostname of the link with the current page location
if (window.location.hostname === new URL(href).hostname) {
// Use the history API to navigate to the new page
history.pushState(null, null, href);
} else {
// Continue with the default behavior
window.location.href = href;
}
});
});

In this example, we use querySelectorAll() to get all links with the class "my-link", and then loop through each link using forEach(). For each link, we add an event listener for when the link is clicked. Inside the event listener, we prevent the default behavior of the link using preventDefault(), and then get the href attribute of the link using getAttribute(). We then use new URL() to create a new URL object from the href, and compare the hostname of the link with the hostname of the current page location using window.location.hostname. If the hostnames match, we use the history.pushState() method to navigate to the new page without reloading the page. If the hostnames do not match, we continue with the default behavior and navigate to the new page using window.location.href.

Conclusion

In this guide, we’ve explored the differences between window.location and window.history in JavaScript and provided guidance on when to use each of them. Remember to use window.location to manipulate the URL of the current page and window.history to manipulate the browser history. If you need to change the URL without reloading the page, use pushState() or replaceState(), and if you need to reload the page or load a new page, use assign() or replace(). Be mindful of the potential impact on the user’s browsing experience and use client-side router libraries to manage application navigation.

Level Up Coding

Thanks for being a part of our community! Before you go:

🚀👉 Join the Level Up talent collective and find an amazing job


Browser navigation: A Guide to window.location and window.history in JavaScript was originally published in Level Up Coding on Medium, where people are continuing the conversation by highlighting and responding to this story.


This content originally appeared on Level Up Coding - Medium and was authored by Aleksandr Guzenko


Print Share Comment Cite Upload Translate Updates
APA

Aleksandr Guzenko | Sciencx (2023-03-22T02:21:09+00:00) Browser navigation: A Guide to window.location and window.history in JavaScript. Retrieved from https://www.scien.cx/2023/03/22/browser-navigation-a-guide-to-window-location-and-window-history-in-javascript/

MLA
" » Browser navigation: A Guide to window.location and window.history in JavaScript." Aleksandr Guzenko | Sciencx - Wednesday March 22, 2023, https://www.scien.cx/2023/03/22/browser-navigation-a-guide-to-window-location-and-window-history-in-javascript/
HARVARD
Aleksandr Guzenko | Sciencx Wednesday March 22, 2023 » Browser navigation: A Guide to window.location and window.history in JavaScript., viewed ,<https://www.scien.cx/2023/03/22/browser-navigation-a-guide-to-window-location-and-window-history-in-javascript/>
VANCOUVER
Aleksandr Guzenko | Sciencx - » Browser navigation: A Guide to window.location and window.history in JavaScript. [Internet]. [Accessed ]. Available from: https://www.scien.cx/2023/03/22/browser-navigation-a-guide-to-window-location-and-window-history-in-javascript/
CHICAGO
" » Browser navigation: A Guide to window.location and window.history in JavaScript." Aleksandr Guzenko | Sciencx - Accessed . https://www.scien.cx/2023/03/22/browser-navigation-a-guide-to-window-location-and-window-history-in-javascript/
IEEE
" » Browser navigation: A Guide to window.location and window.history in JavaScript." Aleksandr Guzenko | Sciencx [Online]. Available: https://www.scien.cx/2023/03/22/browser-navigation-a-guide-to-window-location-and-window-history-in-javascript/. [Accessed: ]
rf:citation
» Browser navigation: A Guide to window.location and window.history in JavaScript | Aleksandr Guzenko | Sciencx | https://www.scien.cx/2023/03/22/browser-navigation-a-guide-to-window-location-and-window-history-in-javascript/ |

Please log in to upload a file.




There are no updates yet.
Click the Upload button above to add an update.

You must be logged in to translate posts. Please log in or register.