BOM allows JavaScript to communicate with the web browser. It is made from a few different components: history, location, navigator, screen and document. This tutorial covers the location property.
You will learn all about BOM location object and ways to work with it. You will learn how to complete the JavaScript location object and assign a method to use JavaScript redirect functionality. You will also learn how you can make JavaScript get URL, hostname, pathname, and protocol of the current page.
Contents
JavaScript Window Location: Main Tips
- JavaScript
window.location
object is used to get information about the current address (URL). - Using this object, you can use JavaScript redirect if you want the user to be redirected to a new webpage.
- The
window
prefix is not necessary.
Using window.location.href
First, we have to get familiar with the window.location.href
method. Basically, it makes JavaScript get URL of the current webpage. Remember you don't need to use the window
prefix necessarily.
Take a look at the example below. Remember you can always see how it works by clicking Try it Live button:
Properties To Use
Using this method, you can also take advantage of various properties. While each of them is equally simple to use, they serve different purposes. We will now review each of them, to make sure you get all the information you need.
Code examples will also be provided. Make sure to try running them in the code editor, and see how it works.
hostname
The JavaScript window.location.hostname
method gives the name of the current page internet host:
pathname
The JavaScript window.location.pathname
method gives the pathname of the current webpage:
protocol
The window.location.protocol
method gives the protocol of the current webpage:
assign
You can also perform JavaScript redirect using the window.location.assign()
method which loads a new document:
function newDocument() {
window.location.assign("https://www.bitdegree.org/")
}
JavaScript Window Location: Summary
- You can use JavaScript
window.location
object to get some information about the current URL. - You can use JavaScript
window.location
object has multiple properties and a method. - You can use JavaScript redirect to URL using the
window.location.assign()
method. - You can use these properties to get the name of an internet host, pathname, and the protocol of the current page.