JavaScript Window Location



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


Window Location

window.location The object can be written without the window prefix. Some examples:

Some examples:

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

  • location.pathname Returns the current page The path and file name

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

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


Window Location Href

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

Example

Return the entire URL (of the current page):

<script>

document.write(location.href);

</script>

The output of the above code is:

##http://www.php.cn/js/js-window- location.html



Window Location Pathname

location.pathname property returns the pathname of the URL.

Example

Return the path name of the current URL:

<script>

document.write(location.pathname);

</script>
The output of the above code is:

/js/js-window-location.html



Window Location Assign

location.assign() method loads a new document.

Instance

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>php中文网(php.cn)</title>
</head>
<head>
<script>
function newDoc(){
	window.location.assign("http://www.php.cn")
}
</script>
</head>
<body>

<input type="button" value="加载新文档" onclick="newDoc()">

</body>
</html>

Run instance»Click the "Run instance" button to view the online instance