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 variable to do with as I please.
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.
URL Info Access
JavaScript provides you with many methods to retrieve and change the current URL, which is displayed in the browser's address bar. All these methods use the Location object, which is a property of the Window object. You can read the current Location object by reading window.location:
var currentLocation = window.location;
Basic URL Structure
<protocol>//<hostname>:<port>/<pathname><search><hash>
protocol: Specifies the protocol name be used to access the resource on the Internet. (HTTP (without SSL) or HTTPS (with SSL))
hostname: Host name specifies the host that owns the resource. For example, www.stackoverflow.com. A server provides services using the name of the host.
port: A port number used to recognize a specific process to which an Internet or other network message is to be forwarded when it arrives at a server.
pathname: The path gives info about the specific resource within the host that the Web client wants to access. For example, /index.html.
search: A query string follows the path component, and provides a string of information that the resource can utilize for some purpose (for example, as parameters for a search or as data to be processed).
hash: The anchor portion of a URL, includes the hash sign (#).
With these Location object properties you can access all of these URL components and what they can set or return:
href - the entire URL
protocol - the protocol of the URL
host - the hostname and port of the URL
hostname - the hostname of the URL
port - the port number the server uses for the URL
pathname - the path name of the URL
search - the query portion of the URL
hash - the anchor portion of the URL
origin - the window.location.protocol + '//' + window.location.host
I hope you got your answer..
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.
Gets the current page URL:
window.location.href
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
also, if your page has 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
To get the path, you can use:
console.log('document.location', document.location.href);
console.log('location.pathname', window.location.pathname); // Returns path only
console.log('location.href', window.location.href); // Returns full URL
Open Developer Tools, type in the following in the console and press Enter.
window.location
Ex: Below is the screenshot of the result on the current page.
Grab what you need from here. :)
Use: window.location.href.
As noted above, document.URL doesn't update when updating window.location. See MDN.
Use window.location.href to get the complete URL.
Use window.location.pathname to get URL leaving the host.
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');
For complete URL with query strings:
document.location.toString()
For host URL:
window.location
// http://127.0.0.1:8000/projects/page/2?name=jake&age=34
let url = new URL(window.location.href);
/*
hash: ""
host: "127.0.0.1:8000"
hostname: "127.0.0.1"
href: "http://127.0.0.1:8000/projects/page/2?username=jake&age=34"
origin: "http://127.0.0.1:8000"
password: ""
pathname: "/projects/page/2"
port: "8000"
protocol: "http:"
search: "?name=jake&age=34"
username: ""
*/
url.searchParams.get('name')
// jake
url.searchParams.get('age')
// 34
url.searchParams.get('gender')
// null
To get the path, you can use:
http://www.example.com:8082/index.php#tab2?foo=789
Property Result
------------------------------------------
window.location.host www.example.com:8082
window.location.hostname www.example.com
window.location.port 8082
window.location.protocol http:
window.location.pathname index.php
window.location.href http://www.example.com:8082/index.php#tab2
window.location.hash #tab2
window.location.search ?foo=789
window.location.origin https://example.com
var currentPageUrlIs = "";
if (typeof this.href != "undefined") {
currentPageUrlIs = this.href.toString().toLowerCase();
}else{
currentPageUrlIs = document.location.toString().toLowerCase();
}
The above code can also help someone
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"
For those who want an actual URL object, potentially for a utility which takes URLs as an argument:
const url = new URL(window.location.href)
https://developer.mozilla.org/en-US/docs/Web/API/URL
Nikhil Agrawal's answer is great, just adding a little example here you can do in the console to see the different components in action:
If you want the base URL without path or query parameter (for example to do AJAX requests against to work on both development/staging AND production servers), window.location.origin is best as it keeps the protocol as well as optional port (in Django development, you sometimes have a non-standard port which breaks it if you just use hostname etc.)
You have multiple ways to do this.
1:
location.href;
2:
document.URL;
3:
document.documentURI;
Use this:
var url = window.location.href;
console.log(url);
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.
The way to get the current location object is window.location.
Compare this to document.location, which originally only returned the current URL as a string. Probably to avoid confusion, document.location was replaced with document.URL.
And, all modern browsers map document.location to window.location.
In reality, for cross-browser safety, you should use window.location rather than document.location.
location.origin+location.pathname+location.search+location.hash;
and
location.href
does the same.
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('/'));
Short
location+''
let url = location+'';
console.log(url);
Getting the current URL with JavaScript :
window.location.toString();
window.location.href
if you are referring to a specific link that has an id this code can help you.
$(".disapprove").click(function(){
var id = $(this).attr("id");
$.ajax({
url: "<?php echo base_url('index.php/sample/page/"+id+"')?>",
type: "post",
success:function()
{
alert("The Request has been Disapproved");
window.location.replace("http://localhost/sample/page/"+id+"");
}
});
});
I am using ajax here to submit an id and redirect the page using window.location.replace. just add an attribute id="" as stated.
let url = new URL(window.location.href);
console.log(url.href);
Use the above code to get the current URL of the website.
or try this - https://bbbootstrap.com/code/get-current-url-javascript-54628697
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 );
});
I'm trying to create a bookmarklet (something I've never done) that will read the URL and check if it ends with "/directory". If it does, I want to remove "/directory". If it doesn't, I want to add it.
I'm using the following to successfully append the directory to the URL, but I don't know how to check if it's already there or delete it if it is.
javascript: window.location = window.location.protocol + '//' + window.location.hostname + window.location.pathname + '/directory';
This will do it:
var URL = window.location.href; window.location.href = /\/directory$/.test(URL) ? URL.replace(/\/directory$/, '') : URL + '/directory';
Checks if the url ends with /directory if does, removes it, else adds it.
I'm making an ebay template for myself, and I want to use a name anchor to jump to different section on the page template. But Ebay adds something to the URL therefore breaking the name anchor.
Since this seems to be Firefox related only, someone suggested that I need to strip "&bv=mozilla" from the URL then it would work. If there are any javascript experts out here that can help me out, I would highly appreciate it.
var documentUrl = location.href;
var newUrl = documentUrl.replace("&bv=mozilla","");
Try this:
var url = location.protocol + '//' + location.host + location.pathname;
or this:
var url = location.protocol + '//' + location.host + ':' + location.port + location.pathname;
if it is on the same page.
Otherwise, you could try this:
var url = 'insert URL here';
var new_url = url.substring(0, url.indexOf('?'));
See substring, indexOf and window.location.
I'm looking for a neat way of getting the URL of the current document in Javascript.
The URL should be clean of parameters (?parameter1=bla¶meter2=bla)
The URL should be clean of hash tags (#jumppoint)
http/https should be removed/consolidated into http
I know i can get the current URL with location.href and then use some regular expressions to clean it up but maybe there is a nicer/cleaner solution for getting rid of the junk?
There are many other parameters than the href in window.location. See full reference here: https://developer.mozilla.org/en/DOM/window.location
What you are looking for as a starter might be the window.location.hostname:
"the host name (without the port number or square
brackets)."
From the example URL http://[www.example.com]:80/search?q=devmo#test the hostname will be www.example.com.
If you also want to include the path and force a http:// protocol, try:
'http://' + window.location.hostname + window.location.pathname;
As a side note, a nifty trick to get the same parameters from another URL than the window.location is to create an empty anchor:
var a = document.createElement('a');
a.href = 'http://www.example.com:80/search?q=devmo#test';
console.log('http://' + a.hostname + a.pathname);
None of the given answers address the fact that the protocol can be http or https as in the OPs title. To accommodate this I suggest:
document.location.protocol +"//"+ document.location.hostname + document.location.pathname
The Location object got what you need
window.location.hostname + window.location.pathname
You have document.location object, so:
var oLoc = document.location,
sUrl = oLoc.protocol + oLoc.hostname;
// or "http://" + oLoc.hostname
You can use these replacement functions to remove the hash and search arguments and normalize https to http:
url = url.replace(/#[^#]*$/, "").replace(/\?[^\?]*$/, "").replace(/^https:/, "http:");
Or, if all you really want is the domain and path, you can just use this:
window.location.hostname + window.location.pathname
Please try this snippet:
if (!window.location.origin){
// For IE
window.location.origin = window.location.protocol + "//" + (window.location.port ? ':' + window.location.port : '');
}
url = window.location.origin + window.location.pathname;
document.write('Origin url: ' + url);
This page indicates that you could probably use window.location.host to get the part you're actually interested in. I haven't tested it, though.
Try:
window.location.hostname;
I want to be able to produce a URL based on certain properties and then go to the new URL in javascript.
Here is what I have so far:
triggerNumber = document.findcontrol(txtTrigNo).text;
hostAddress= top.location.host.toString();
url = "http://" + hostAddress "/" + triggerNumber
How do I navigate to the new URL?
Simply try:
window.location = url;
But before trying to do that, you have to make sure the page at the address "http://" + hostAddress "/" + triggerNumber exists. For example by putting valid triggerNumbers in an array and check if it exists or not. So:
//Not sure if at the end it should be .text or .value or .value()
triggerNumber = document.findcontrol(txtTrigNo).text;
var validTriggers = [123, 456, 789];
if (validTriggers.indexOf(parseInt(triggerNumber)) == -1) {
alert("Invalid trigger number");
} else {
hostAddress= top.location.host.toString();
url = "http://" + hostAddress "/" + triggerNumber;
}
Finally, if the destination is a server-side page (php, asp, etc), the address usually looks like this:
"http://" + hostAddress "/trigger.php?id=" + triggerNumber;
but you'd better use forms for this.
Edit: As Cerbrus suggested, validating the values with javascript is a good way to tell the user about his errors before navigating away from the page. But to make sure the correct data is sent to server, it is important to do the validation in the server-side code, too.
In this example, in case of an invalid trigger number the user may finally see a 404 error; but with sensitive information worse things can happen.
What you need is:
document.location.href = url;
After you have the URL in the url variable.
To get value of input element have:
var triggerNumber = document.getElementById("txtTrigNo").value;
This will get the hostname and port of the server, and concatenate the value of the element onto the end, and then go to the resulting URL.
var triggerNumber = document.getElementById("txtTrigNo").value();
var url = "http://"+window.location.host+"/"+triggerNumber;
window.location = url;