JavaScript Window Location
- Previous Page JS Screen
- Next Page JS History
The window.location object can be used to obtain the current page address (URL) and redirect the browser to a new page.
Window Location
window.location The object can be written without the 'window' prefix.
Some examples:
- window.location.href returns the href (URL) of the current page
- window.location.hostname returns the domain name of the web host
- window.location.pathname returns the path or file name of the current page
- window.location.protocol returns the used web protocol (http: or https:)
- window.location.assign loads a new document
Window Location Href
window.location.href
The property returns the URL of the current page.
Example
Display the href (URL) of the current page:
document.getElementById("demo").innerHTML = "The page location is " + window.location.href;
The result is:
The page location is http://www.codew3c.com/js/js_window_location.asp
Window Location Host Name
window.location.hostname
The property returns the name of the Internet host (current page).
Example
Display the name of the host:
document.getElementById("demo").innerHTML = "The page hostname is " + window.location.hostname;
The result is:
The page hostname is www.codew3c.com
Window Location Path Name
window.location.pathname
The property returns the path name of the current page.
Example
Display the path name of the current URL:
document.getElementById("demo").innerHTML = "The page path is " + window.location.pathname;
The result is:
The page path is /js/js_window_location.asp
Window Location Protocol
window.location.protocol
The property returns the web protocol of the page.
Example
Display web protocol:
document.getElementById("demo").innerHTML = "The page protocol is " + window.location.protocol;
The result is:
The page protocol is http:
Window Location Port
window.location.port
Property returns the number of the internet host port (current page).
Example
Show the port number of the host:
document.getElementById("demo").innerHTML = "Port number is: " + window.location.port;
Most browsers do not display the default port number (http is 80, https is 443).
Window Location Assign
window.location.assign()
Method to load a new document.
Example
Load new document:
<html> <head> <script> function newDoc() { window.location.assign("https://www.codew3c.com") } </script> </head> <body> <input type="button" value="Load new document" onclick="newDoc()"> </body> </html>
- Previous Page JS Screen
- Next Page JS History