JavaScript Window Location


The window.location object is used to get the address (URL) of the current page and redirect the browser to a new page.


Window Location

window.location objects can be written without the window prefix.

Some examples:

  • location.hostname returns the domain name of the web host

  • location.pathname returns the path and file name of the current page

  • location.port returns the port of the web host (80 or 443)

  • location.protocol returns the web protocol used (http:or https:)


Window Location Href

The location.href property returns the URL of the current page.

Example

Returns the entire url of the current page:

<script>
document.write(location.href);
</script>

Output is:

https://www.tutorialfish.com/js-browser-bom/javascript-window-location.html


Window Location Pathname

The location.pathname property returns the path name of the URL.

Example

Returns the path name of the current url:

<script>
document.write(location.pathname);
</script>

Output is:

/js-browser-bom/javascript-window-location.html


Window Location Assign

The location.assign() method loads the new document.

Example

Load a new document:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>TutorialFish (tutorialfish.com)</title>
<script>
function newDoc(){
     window.location.assign("https://www.tutorialfish.com")
}
</script>
</head>
<body>
<input type="button" value="Load new document" onclick="newDoc()">
</body>
</html>

Try It!