Home >Web Front-end >JS Tutorial >Detailed explanation of window location and history objects in JavaScript programming_Basic knowledge

Detailed explanation of window location and history objects in JavaScript programming_Basic knowledge

WBOY
WBOYOriginal
2016-05-16 15:34:491399browse

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.
  • The window.location 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 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
Return the entire URL (of the current page):

<script>

document.write(location.href);

</script>



Window Location Pathname
The location.pathname property returns the pathname of the URL.
Example
Returns the pathname 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
The location.assign() method loads a new document.
Example
Load a new document:

<html>
<head>
<script>
function newDoc()
 {
 window.location.assign("http://www.w3cschool.cc")
 }
</script>
</head>
<body>

<input type="button" value="Load new document" onclick="newDoc()">

</body>
</html>


Window History
The window.history object does not need to use the window prefix when writing.
To protect user privacy, JavaScript's methods of accessing this object are restricted.
Some methods:

  • history.back() - Same as clicking the back button in the browser
  • history.forward() - Same as clicking the button forward in the browser

Window History Back

The history.back() method loads the previous URL in the history list.
This is the same as clicking the back button in your browser:
Example
Create a back button on the page:

<html>
<head>
<script>
function goBack()
 {
 window.history.back()
 }
</script>
</head>
<body>

<input type="button" value="Back" onclick="goBack()">

</body>
</html>


Window History Forward
The history forward() method loads the next URL in the history list.
This is the same as clicking the forward button in your browser:
Example
Create a forward button on the page:

<html>
<head>
<script>
function goForward()
 {
 window.history.forward()
 }
</script>
</head>
<body>

<input type="button" value="Forward" onclick="goForward()">

</body>
</html>

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn