It’s Festive Season! Enjoy 30% Off

Use code FESTIVE30 at checkout

Code has been added to clipboard!

Tips and Tricks on Using JavaScript Redirect Method

Reading time 3 min
Published Aug 8, 2017
Updated Oct 2, 2019

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.

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:

Example
document.write("Location of the page " + location.href);
Theory is great, but we recommend digging deeper!

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:

Example
document.write("Hostname: " + location.hostname);

pathname

The JavaScript window.location.pathname method gives the pathname of the current webpage:

Example
document.write(location.pathname);

protocol

The window.location.protocol method gives the protocol of the current webpage:

Example
document.write("Protocol of the page: " + location.protocol);

assign

You can also perform JavaScript redirect using the window.location.assign() method which loads a new document:

Example

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.