In this article, we will look into another built-in JavaScript object named as location. Location object provides us, information about the currently loaded URL details like host name, port and protocol etc. We can get complete details of a URI by using this object. Let's dig into this object deeply by an ASP.NET sample. Create an ASP.NET web application in VS 2008 and name it as JSLocationSample.
Now, design the Default.aspx as shown below:
I added few buttons and a textbox to get the details of the currently loaded URL like host name, port number, query string parameters etc. Now, add below JavaScript to Default.aspx:
<script type="text/javascript">
function showURLInfo()
{
for (var property in location)
{
document.getElementById("txtURL").value += property + "-->" + ((location[property] == "") ? "Not Present" : location[property]) + "\r\n";
}
}
function reloadPage()
{
location.reload();
}
function navigateNext()
{
location.assign("NewPage.aspx?Name=YYY");
}
function getQueryString()
{
if (location.search)
{
var params = location.search.split('&');
for (var i = 0; i < params.length; i++)
{
var param = params[i].split('=');
alert(param[0].toString().replace('?', '') + ":" + param[1]);
}
}
}
</script>
On click of reload button, we can reload the page using location's reload().
On click of Next Page button, we can move to next page using location's assign().
On click of Show Info button, we can get details of the loaded URL.
On click of Get parameters button, we can get the details of the query string using location's search property.
Add some few more pages as shown in below figure and set StartUp.aspx as start page and run the application:
The output will be shown below:
We can use location's assign() to move to another page without using server side methods like response's Redirect or server's Transfer.
By using location object, we can access below properties of the browser's URI:
Property Name |
Description |
host |
Host |
hostname |
Host Name |
href |
URL |
pathname |
-- |
port |
Port Number |
protocol |
Protocol Name |
search |
Query String Parameters |
Methods: |
|
reload() |
Reload the page |
assign() |
Navigate to new page in current window |
I am ending the things here. I hope this article will be helpful for all.