What's the difference between window.location and document.location?

The window.location property

The location property of a window (i.e. window.location) is a reference to a Location object; it represents the current URL of the document being displayed in that window.

Since window object is at the top of the scope chain, so properties of the window.location object can be accessed without the window prefix. For example window.location.href can be written as location.href. The following section will show you how to get the URL of page as well as hostname, protocol, etc. using the location object property of the window object.

You can use the window.location.href property to get the entire URL of the current page.

Example

Following example demonstrates the usage of window.location.href to get the URL of page −

<!DOCTYPE html>
<html lang="en">
<meta charset="utf-8">
<title>JavaScript Get Current URL</title>
<body>
<script>
function getURL() {
}
</script>
<button type="button" onclick="getURL();">Get Page URL</button>
</body>
</html>


On executing the above program, it will display a button saying Get Page URL. On clicking this button, the URL of the current page will be displayed. If we click on the button mentioned as Get Page URL, we will get the output as current URL.

The document.location property

This is a read-only property which returns the URL of the current document. Following is an example of the document.location property in JavaScript −

<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document.location Properties</title>
<body>
<script>
document.write("The pathname of this file is:"+ document.location.pathname + "<br>");
document.write("The Protocol used is:"+ document.location.protocol + "<br>");
</script>
</body>
</html>


To make the document.location to load a URL, it should be assigned to a string and then the URL in the string will be loaded. To assign or load by using a new document, the following example can be used.

Example

<!DOCTYPE html>
<html>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document.location </title>
<body>
<h2>Document.location</h2>
<script>
function newPage() {
document.location.assign("https://www.tutorialspoint.com/");
}
</script>
<button type="button" onclick="newPage() ;">
Click
</button>
</body>
</html>


Difference Between window.location & document.location

Both the objects window.location and document.location are used for getting the URL, but the difference is −

• The window.location is read and write in all browser
• Whereas, document.location is read-only in Internet Explorer and read/write in Gecko-based browsers.