Check if Homepage JavaScript
In this tutorial, we will learn how to check if the current page a user is on is the homepage in JavaScript. We will assume your homepage is the root URL path.
Get the Current Pathname
The easiest way to find out whether the current location is the homepage is to get the current pathname using window.location.pathname. We can then use an if
statement to check if the pathname is equal to /
(forward slash).
current = window.location.pathname;
if (current == '/') {
console.log('Is the homepage.')
} else {
console.log('Not on the homepage.')
}
Not on the homepage.
Conclusion
You can apply this technique to validate any pathname, not just the homepage.