Every
now and then we need current page URL, it’s very easy to get current page URL
at server side(C#), but people found it’s tricky while we need to get current
page URL on client side, but it’s not so tricky.
We can
get current page URL with both jQuery and JavaScript as:
$(document).ready(function () {
//with jquery location object
var path = $(location).attr('href');
//with javascript code
var path = window.location.href;
});
|
In jQuery
we can use “location” object to get the more details of current page like host,
hash, protocol, pathname, etc.
Same way
we can use “window.location” in JavaScript to get all details of current page
URL.
Let’s
understand this with one example URL:
URL: http://www.testserver.com:8080/test.aspx#tab
JQuery
|
JavaScript
|
Result
|
$(location).attr('href');
|
window.location.href
|
http://www.testserver.com
:8080/test.aspx#tab
|
$(location).attr('host');
|
window.location.host
|
www.testserver.com:8080
|
$(location).attr('hostname');
|
window.location.hostname
|
www.testserver.com
|
$(location).attr('port');
|
window.location.port
|
8080
|
$(location).attr('protocol');
|
window.location.protocol
|
http
|
$(location).attr('pathname');
|
window.location.pathname
|
test.aspx
|
$(location).attr('hash');
|
window.location.hash
|
#tab
|
Comments
Post a Comment