The location object contains information about the current URL you’re visiting. It can give you helpful information such as the port number, whether or not the site is using SSL and even allows you to redirect the user.
Clear your script and add this bit of code.
document.write( location.hostname + '<br />' ); // Returns the Server
document.write( location.href + '<br />' ); // Returns the full URL of the page you're on
document.write( location.pathname + '<br />' ); // Returns just the path of URL.
document.write( location.port + '<br />' ); // Returns the port number
document.write( location.protocol + '<br />' ); // Returns http: or https:
document.write( location.search + '<br />' ); // Returns the query string if there is one.
There are a couple of properties of the location object, but we’ll just focus on these 6.
- hostname – This will return the server. This is usually the URL. For example, this would return www.jaskokoyn.com if this was hosted on my site.
- href – This will return the full URL of the current page you’re on.
- pathname – This will return the path of the URL. For example, if you’re on www.yoursite.com/path1/path2/index.html, then you would get /path1/path2/index.html
- port – Returns the current port being used to access the website. Most of the time you’ll get an empty string if the port isn’t present in the URL.
- protocol – Returns http: or https: depending if the server has SSL active or not.
- search – This will return the query of the URL. This is usually the text after the ? in the URL if there is one.
Some of these may return an empty string depending if you’re opening this from an actual site or just opening it in your browser as a file.
One of the most common uses of the location object is to navigate to a new URL. To navigate to a new URL you use the assign() method. You simply pass in the new URL you would like to go to. Add this bit of code to your script.
location.assign( 'http://jaskokoyn.com' );
There’s also another method that does the same thing called replace(). However, this method doesn’t allow the browser to save the previous URL. So the user can’t press the back button. Here’s how you would use it.
location.replace( 'http://jaskokoyn.com' );
location.reload( false ); // Reloads from cache if present.
location.reload( true ); // Reloads from server
The location object can you help you manipulate the URL and redirect the user on certain conditions. For more information about the location object, then go here.