JavaScript Window Location

Location Object

The JavaScript Location object is used to get or set the current URL information. The Location object is part of the window object and can be accessed through the window.location property.

The Location object is often used to obtain the information in the URL address, or refresh the current page, page redirection, etc. For details, see the properties and methods listed below.

Location Object Properties


Properties                       Description


location.hash Set or get the anchor in the URL

location.host Set or get the host (including port number) in the URL

location.hostname Set or get the host name in the URL

location.href Set or get the complete URL (page redirection application)

location.pathname Set or get the path in the URL

location.port Set or get the URL Port number

location.protocol Set or get the protocol used by the URL

location.search Set or get the query string in the URL (usually the content after the ? symbol)

Location object methods

The History object has the following three methods:

location.assign(): Load a new page document

location.reload (): Reload (refresh) the current page

location.replace(): Replace the current document with the new document

JavaScript location.href attribute

The href attribute of the Location object is used to set or get the current complete URL. The syntax is as follows:

location.href = URL

#location.href attribute is most commonly used for page jumps (redirects) in JavaScript

Returns the entire URL (of the current page):

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>php中文网(php.cn)</title> 
<script type="text/javascript">
document.write(location.href);
</script>
</head>
<body>
</body>
</html>

JavaScript location.pathname attribute

The pathname attribute of the Location object is used to set or get the path part of the current URL. The syntax is as follows:

location.pathname = path

Return the path name of the current URL:

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>php中文网(php.cn)</title> 
<script type="text/javascript">
document.write(location.pathname);
</script>
</head>
<body>
</body>
</html>

JavaScript location.assign() method

The assign() method of the Location object is used to load a new document. The syntax is as follows:

location.assign(URL)

Load a new document:

<!DOCTYPE html>
<html>
<head> 
<meta charset="utf-8"> 
<title>php中文网(php.cn)</title> 
<script type="text/javascript">
function setAssign(){
window.location.assign("http://www.php.cn");
}
</script>
</head>
<body>
  <button onclick="setAssign()">加载新文档</button>
</body>
</html>


Continuing Learning
||
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <title>php中文网(php.cn)</title> <script type="text/javascript"> function setAssign(){ window.location.assign("http://www.php.cn"); } </script> </head> <body> <button onclick="setAssign()">加载新文档</button> </body> </html>
submitReset Code