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 );
});
Related
I am trying to do a simple page redirection using window.location.href = ... in Chrome.
For example, the desired URL is http://[hostname]:[port]/Error/Timeout
At first I try use
window.location.href = window.location.host + "/Error/Timeout"
Though I logged the URL generated is correct, it does not work, the page does not redirect at all.
Then I changed to
window.location.href = "/Error/Timeout"
It works! But the URL generated is exactly the same as previous method.
So my question is what makes such difference ?
The window.location.host variable contains only the domain (without the protocol), so you are trying to redirect the user to a non-valid URL, and the browser will not allow it.
The "/Error/Timeout" is a valid URL, because the browser will look at the "/" at the beginning as "part of the current domain", and just use PROTOCOL://HOSTNAME:PORT/ combined with the url you provided.
You could also use:
window.location.href = window.location.protocol + "//" + window.location.hostname + (window.location.port ? (":"+window.location.port):'') + "/Error/Timeout"
Or a much better option:
url = new URL(window.location.href)
url.pathname = "/Error/Timeout"
window.location.href = url.toString()
Below is what I have.
var myString = "http://localhost:8888/www.smart-kw.com/";
alert(myString.indexOf("localhost"));
This give me alert... however if I change var myString = "http://localhost:8888/www.smart-kw.com/"; to var myString = window.location;, it won't work (I don't get alert).
var myString = window.location;
alert(myString.indexOf("localhost"));
window.location is an accessor property, and getting its value gives you an object, not a string, and so it doesn't have an indexOf function. (It's perfectly understandable that people sometimes think it's a string, since when you set its value, the accessor property's setter accepts a string; that is, window.location = "some url"; actually works. But when you get it, you don't get a string.)
You can use window.location.toString(), String(window.location), or window.location.href to get a string for it if you like, or use any of its various properties to check specifics. From the link, given example url http://www.example.com:80/search?q=devmo#test:
hash: The part of the URL that follows the # symbol, including the # symbol. You can listen for the hashchange event to get notified of changes to the hash in supporting browsers.Example: #test
host: The host name and port number.Example: www.example.com:80
hostname: The host name (without the port number).Example: www.example.com
href: The entire URL.Example: http://www.example.com:80/search?q=devmo#test
pathname: The path (relative to the host).Example: /search
port: The port number of the URL.Example: 80
protocol: The protocol of the URL.Example: http:
search: The part of the URL that follows the ? symbol, including the ? symbol.Example: ?q=devmo
For instance, for your quoted example, you might check window.location.hostname === "localhost".
As far as I know window.location is a Location object.
For instance, window.location.href will give you the entire URL.
var url = window.location.href;
alert(url.indexOf("domain"));
But this kind of check is bound to trigger false-positives. You are better using window.location.hostname property which holds the host name part.
var hostname = window.location.hostname;
alert(hostname === "my.domain.com");
I found a way to make this work:
(window.location.href).indexOf("localhost") > -1)
I actually use this for my projects as conditionals and it works just fine.
Is there a way to update the URL programatically without reloading the page?
EDIT: I added something in the title in post .I just want to make it clear that I don't want to reload the page
Yes and no. All the common web browsers has a security measure to prevent that. The goal is to prevent people from creating replicas of websites, change the URL to make it look correct, and then be able to trick people and get their info.
However, some HTML5 compatible web browsers has implemented an History API that can be used for something similar to what you want:
if (history.pushState) {
var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?myNewUrlQuery=1';
window.history.pushState({path:newurl},'',newurl);
}
I tested, and it worked fine. It does not reload the page, but it only allows you to change the URL query. You would not be able to change the protocol or the host values.
For more information:
http://diveintohtml5.info/history.html
https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
Yes - document.location = "http://my.new.url.com"
You can also retrieve it the same way eg.
var myURL = document.location;
document.location = myURL + "?a=parameter";
The location object has a number of useful properties too:
hash Returns the anchor portion of a URL
host Returns the hostname and port of a URL
hostname Returns the hostname of a URL
href Returns the entire URL
pathname Returns the path name of a URL
port Returns the port number the server uses for a URL
protocol Returns the protocol of a URL
search Returns the query portion of a URL
EDIT:
Setting the hash of the document.location shouldn't reload the page, just alter where on the page the focus is. So updating to #myId will scroll to the element with id="myId". If the id doesn't exist I believe nothing will happen? (Need to confirm on various browsers though)
EDIT2: To make it clear, not just in a comment:
You can't update the whole URL with javascript without changing the page, this is a security restriction. Otherwise you could click on a link to a random page, crafted to look like gmail, and instantly change the URL to www.gmail.com and steal people's login details.
You can change the part after the domain on some browsers to cope with AJAX style things, but that's already been linked to by Osiris. What's more, you probably shouldn't do this, even if you could. The URL tells the user where he/she is on your site. If you change it without changing the page contents, it's becomes a little confusing.
You can use :
window.history.pushState('obj', 'newtitle', newUrlWithQueryString)
Use
window.history.replaceState({}, document.title, updatedUri);
To update Url without reloading the page
var url = window.location.href;
var urlParts = url.split('?');
if (urlParts.length > 0) {
var baseUrl = urlParts[0];
var queryString = urlParts[1];
//update queryString in here...I have added a new string at the end in this example
var updatedQueryString = queryString + 'this_is_the_new_url'
var updatedUri = baseUrl + '?' + updatedQueryString;
window.history.replaceState({}, document.title, updatedUri);
}
To remove Query string without reloading the page
var url = window.location.href;
if (url.indexOf("?") > 0) {
var updatedUri = url.substring(0, url.indexOf("?"));
window.history.replaceState({}, document.title, updatedUri);
}
Define a new URL object, assign it the current url, append your parameter(s) to that URL object and finally push it to your browsers state.
var url = new URL(window.location.href);
//var url = new URL(window.location.origin + window.location.pathname) <- flush existing parameters
url.searchParams.append("order", orderId);
window.history.pushState(null, null, url);
Yes
document.location is the normal way.
However document.location is effectively the same as window.location, except for window.location is a bit more supported in older browsers so may be the prefferable choice.
Check out this thread on SO for more info:
What's the difference between window.location and document.location in JavaScript?
Prefix URL changes with a hashtag to avoid a redirect.
This redirects
location.href += '&test='true';
This doesn't redirect
location.href += '#&test='true';
Plain javascript: document.location = 'http://www.google.com';
This will cause a browser refresh though - consider using hashes if you're in need of having the URL updated to implement some kind of browsing history without reloading the page. You might want to look into jQuery.hashchange if this is the case.
You'll need to be more specific. What do you mean by 'update the URL'? It could mean automatically navigating to a different page, which is certainly possible.
If you want to just update the contents of the address bar without reloading the page, see Modify the URL without reloading the page
Yes - document.location.hash for queries
I am wondering how I would get JavaScript to check if a user is on a certain URL so i can build an if statement from the result.
My reasoning is that if a user clicks on a link in the menu and they are currently on trucks.php the javascript will redirect them to a certain page. If they are not on trucks.php they will be directed to a different page.
Cheers guys.
The current location is in location.href.
The location object also contains some other useful fields:
location.hash: The part after the # in the URL
location.host: Hostname including port (if specified)
location.hostname: Just the hostname
location.pathname: The requested URI without protocol/host/port; starting with a /
location.port: The port - only if one is specified in the URL
location.protocol: Usually 'http:' or 'https:' - mind the colon at the end
In your case the most fail-safe way to check if the filename is trucks.php is this:
var parts = location.pathname.split('/');
if(parts[parts.length - 1] == 'trucks.php') {
location.href = 'some-other-page';
}
If you want to redirect without keeping the current page in history, use the following code instead of the location.href assignment:
location.replace('some-other-page');
Use window.location.href to get the current URL, or window.location.pathname to get just the path. For your specific problem, just the path name is required for the solution:
if (window.location.pathname == "/trucks.php")
window.location = "/somewhereelse.php";
Check out the MDC documentation for window.location.
Use window.location
Guys I have a question, hoping you can help me out with this one. I have a bookmarklet;
javascript:q=(document.location.href);void(open('http://other.example.com/search.php?search='+location.href,'_self ','resizable,location,menubar,toolbar,scrollbars,status'));
which takes URL of the current webpage and search for it in another website. When I use this bookmarklet it takes the whole URL including http:// and searches for it. But now I would like to change this bookmarklet so it will take only the www.example.com or just example.com (without http://) and search for this url. Is it possible to do this and can you please help me with this one?
Thank you!
JavaScript can access the current URL in parts. For this URL:
http://css-tricks.com/example/index.html
window.location.protocol = "http"
window.location.host = "css-tricks.com"
window.location.pathname = "/example/index.html"
please check: http://css-tricks.com/snippets/javascript/get-url-and-url-parts-in-javascript/
This should do it
location.href.replace(/https?:\/\//i, "")
Use document.location.host instead of document.location.href. That contains only the host name and not the full URL.
Use the URL api
A modern way to get a part of the URL can be to make a URL object from the url that you are given.
const { hostname } = new URL('https://www.some-site.com/test'); // www.some-site.com
You can of course just pass window location or any other url as an argument to the URL constructor.
Like this
const { hostname } = new URL(document.location.href);
Do you have control over website.com other.example.com? This should probably be done on the server side.
In which case:
preg_replace("/^https?:\/\/(.+)$/i","\\1", $url);
should work. Or, you could use str_replace(...), but be aware that that might strip 'http://' from somewhere inside the URL:
str_replace(array('http://','https://'), '', $url);
EDIT: or, if you just want the host name, you could try parse_url(...)?
Using javascript replace via regex matching:
javascript:q=(document.location.href.replace(/(https?|file):\/\//,''));void(open('http://website.com/search.php?search='+q,'_self ','resizable,location,menubar,toolbar,scrollbars,status'));
Replace (https?|file) with your choice, e.g. ftp, gopher, telnet etc.