Home » JavaScript » JavaScript Window Location

JavaScript Window Location

The JavaScript window.location object of a window contain information about current url. It can also be used without the window prefix. It can be used in many forms like:

  • location.href : It returns the URl of the current page opened.
  • loaction.pathname : It returns the path and filename of the current opened webpage.
  • location.assign : It is used to load a new document.

Get Page URL

The window.location.href property is used to get the entire URL of the current page.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript Window Location Object </title>
</head>
<body>
<script>
function getURL() {
alert("The URL of this page is: " + window.location.href);
}
</script>
<button type="button" onclick="getURL();">Get Page URL</button>
</body>
</html>

Output

JavaScript Window Location Object

Load New Document

The assign() method of the location object can be used to open another url on a new window.

Example

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript Window Another URL Location </title>
</head>
<body>
<script>
function loadHomePage() {
window.location.assign("http://coderepublics.com");
}
</script>
<button type="button" onclick="loadHomePage();">Load Home Page</button>
</body>
</html>

Output

JavaScript Window Another URL Location

Reload Page Dynamically

The reload() method is used to reload the current page. In the example below, a button is given, clicking on which the page will get reloaded entirely.


<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title> JavaScript Window Reload Location </title>
</head>
<body>
<script>
function forceReload() {
window.location.reload(true);
}
</script>
<button type="button" onclick="forceReload();">Reload Page</button>
</body>
</html>

Output

JavaScript Window Reload Location

There is another method Javascript location.reload(true) that also helps you to refresh the whole webpage.









Follow Us: