All I want is to get the website URL. Not the URL as taken from a link. On the page loading I need to be able to grab the full, current URL of the website and set it as a va
In jstl we can access the current URL path using pageContext.request.contextPath
. If you want to do an Ajax call, use the following URL.
url = "${pageContext.request.contextPath}" + "/controller/path"
Example: For the page http://stackoverflow.com/posts/36577223
this will give http://stackoverflow.com/controller/path
.
You can get the current URL location with a hash tag by using:
JavaScript:
// Using href
var URL = window.location.href;
// Using path
var URL = window.location.pathname;
jQuery:
$(location).attr('href');
window.location.href
to get the complete URL. window.location.pathname
to get URL leaving the host.Use: window.location.href
.
As noted above, document.URL
doesn't update when updating window.location
. See MDN.
Adding result for quick reference
window.location;
Location {href: "https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript",
ancestorOrigins: DOMStringList,
origin: "https://stackoverflow.com",
replace: ƒ, assign: ƒ, …}
document.location
Location {href: "https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript",
ancestorOrigins: DOMStringList,
origin: "https://stackoverflow.com",
replace: ƒ, assign: ƒ
, …}
window.location.pathname
"/questions/1034621/get-the-current-url-with-javascript"
window.location.href
"https://stackoverflow.com/questions/1034621/get-the-current-url-with-javascript"
location.hostname
"stackoverflow.com"
Use window.location
for read and write access to the location object associated with the current frame. If you just want to get the address as a read-only string, you may use document.URL
, which should contain the same value as window.location.href
.