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
OK, getting the full URL of the current page is easy using pure JavaScript. For example, try this code on this page:
window.location.href;
// use it in the console of this page will return
// http://stackoverflow.com/questions/1034621/get-current-url-in-web-browser"
The
window.location.href
property returns the URL of the current page.
document.getElementById("root").innerHTML = "The full URL of this page is:<br>" + window.location.href;
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript</h2>
<h3>The window.location.href</h3>
<p id="root"></p>
</body>
</html>
Just not bad to mention these as well:
if you need a relative path, simply use window.location.pathname
;
if you'd like to get the host name, you can use window.location.hostname
;
and if you need to get the protocol separately, use window.location.protocol
hash
tag, you can get it like: window.location.hash
.So window.location.href
handles all in once... basically:
window.location.protocol + '//' + window.location.hostname + window.location.pathname + window.location.hash === window.location.href;
//true
Also using window
is not needed if already in window scope...
So, in that case, you can use:
location.protocol
location.hostname
location.pathname
location.hash
location.href
Getting the current URL with JavaScript :
window.location.toString();
window.location.href
Firstly check for page is loaded completely in
browser,window.location.toString();
window.location.href
then call a function which takes url, URL variable and prints on console,
$(window).load(function(){
var url = window.location.href.toString();
var URL = document.URL;
var wayThreeUsingJQuery = $(location).attr('href');
console.log(url);
console.log(URL);
console.log(wayThreeUsingJQuery );
});
You can get the full link of the current page through location.href
and to get the link of the current controller, use:
location.href.substring(0, location.href.lastIndexOf('/'));
Use:
window.location.href
As noted in the comments, the line below works, but it is bugged for Firefox.
document.URL
See URL of type DOMString, readonly.
Try
location+''
let url = location+'';
console.log(url);