Get current URL with jQuery? - javascript
I am using jQuery. How do I get the path of the current URL and assign it to a variable?
Example URL:
http://localhost/menuname.de?foo=bar&number=0
To get the path, you can use:
var pathname = window.location.pathname; // Returns path only (/path/example.html)
var url = window.location.href; // Returns full URL (https://example.com/path/example.html)
var origin = window.location.origin; // Returns base URL (https://example.com)
In pure jQuery style:
$(location).attr('href');
The location object also has other properties, like host, hash, protocol, and pathname.
http://www.refulz.com:8082/index.php#tab2?foo=789
Property Result
------------------------------------------
host www.refulz.com:8082
hostname www.refulz.com
port 8082
protocol http:
pathname index.php
href http://www.refulz.com:8082/index.php#tab2
hash #tab2
search ?foo=789
var x = $(location).attr('<property>');
This will work only if you have jQuery. For example:
<html>
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.2.6/jquery.min.js"></script>
<script>
$(location).attr('href'); // http://www.refulz.com:8082/index.php#tab2
$(location).attr('pathname'); // index.php
</script>
</html>
If you need the hash parameters present in the URL, window.location.href may be a better choice.
window.location.pathname
=> /search
window.location.href
=> www.website.com/search#race_type=1
You'll want to use JavaScript's built-in window.location object.
Just add this function in JavaScript, and it will return the absolute path of the current path.
function getAbsolutePath() {
var loc = window.location;
var pathName = loc.pathname.substring(0, loc.pathname.lastIndexOf('/') + 1);
return loc.href.substring(0, loc.href.length - ((loc.pathname + loc.search + loc.hash).length - pathName.length));
}
I hope it works for you.
window.location is an object in javascript. it returns following data
window.location.host #returns host
window.location.hostname #returns hostname
window.location.path #return path
window.location.href #returns full current url
window.location.port #returns the port
window.location.protocol #returns the protocol
in jquery you can use
$(location).attr('host'); #returns host
$(location).attr('hostname'); #returns hostname
$(location).attr('path'); #returns path
$(location).attr('href'); #returns href
$(location).attr('port'); #returns port
$(location).attr('protocol'); #returns protocol
This is a more complicated issue than many may think. Several browsers support built-in JavaScript location objects and associated parameters/methods accessible through window.location or document.location. However, different flavors of Internet Explorer (6,7) don't support these methods in the same way, (window.location.href? window.location.replace() not supported) so you have to access them differently by writing conditional code all the time to hand-hold Internet Explorer.
So, if you have jQuery available and loaded, you might as well use jQuery (location), as the others mentioned because it resolves these issues. If however, you are doing-for an example-some client-side geolocation redirection via JavaScript (that is, using Google Maps API and location object methods), then you may not want to load the entire jQuery library and write your conditional code that checks every version of Internet Explorer/Firefox/etc.
Internet Explorer makes the front-end coding cat unhappy, but jQuery is a plate of milk.
For the host name only, use:
window.location.hostname
This will also work:
var currentURL = window.location.href;
java-script provides many methods to retrieve current URL which is displayed in browser's address bar.
Test URL :
http://
stackoverflow.com/questions/5515310/get-current-url-with-jquery/32942762
?
rq=1&page=2&tab=active&answertab=votes
#
32942762
resourceAddress.hash();
console.log('URL Object ', webAddress);
console.log('Parameters ', param_values);
Function:
var webAddress = {};
var param_values = {};
var protocol = '';
var resourceAddress = {
fullAddress : function () {
var addressBar = window.location.href;
if ( addressBar != '' && addressBar != 'undefined') {
webAddress[ 'href' ] = addressBar;
}
},
protocol_identifier : function () { resourceAddress.fullAddress();
protocol = window.location.protocol.replace(':', '');
if ( protocol != '' && protocol != 'undefined') {
webAddress[ 'protocol' ] = protocol;
}
},
domain : function () { resourceAddress.protocol_identifier();
var domain = window.location.hostname;
if ( domain != '' && domain != 'undefined' && typeOfVar(domain) === 'string') {
webAddress[ 'domain' ] = domain;
var port = window.location.port;
if ( (port == '' || port == 'undefined') && typeOfVar(port) === 'string') {
if(protocol == 'http') port = '80';
if(protocol == 'https') port = '443';
}
webAddress[ 'port' ] = port;
}
},
pathname : function () { resourceAddress.domain();
var resourcePath = window.location.pathname;
if ( resourcePath != '' && resourcePath != 'undefined') {
webAddress[ 'resourcePath' ] = resourcePath;
}
},
params : function () { resourceAddress.pathname();
var v_args = location.search.substring(1).split("&");
if ( v_args != '' && v_args != 'undefined')
for (var i = 0; i < v_args.length; i++) {
var pair = v_args[i].split("=");
if ( typeOfVar( pair ) === 'array' ) {
param_values[ decodeURIComponent( pair[0] ) ] = decodeURIComponent( pair[1] );
}
}
webAddress[ 'params' ] = param_values;
},
hash : function () { resourceAddress.params();
var fragment = window.location.hash.substring(1);
if ( fragment != '' && fragment != 'undefined')
webAddress[ 'hash' ] = fragment;
}
};
function typeOfVar (obj) {
return {}.toString.call(obj).split(' ')[1].slice(0, -1).toLowerCase();
}
protocol « Web-browsers use Internet Protocol by following some rules for communication between WebHosted Applications and Web Client(Browser). (http = 80, https (SSL) = 443, ftp = 21, etc.)
EX: With default port numbers
<protocol>//<hostname>:<port>/<pathname><search><hash>
https://en.wikipedia.org:443/wiki/Pretty_Good_Privacy
http://stackoverflow.com:80/
(//) « Host is the name given to an end-point(machine on which resource lives) on the Internet.
www.stackoverflow.com - DNS IP Address of an Application (OR) localhost:8080 - localhost
Domain names are which you register by the rules and procedures of the Domain Name System(DNS) tree. DNS servers of someone who manages your domain with IP-Address for addressing purposes. In DNS server hierarchy
the Root name of an stackoverlfow.com is com.
gTLDs - com « stackoverflow (OR) in « co « google
Local system you have to maintain domain's which are not PUBLIC in Host Files.
localhost.yash.com « localhsot - subdomain(web-server), yash.com - maindomain(Proxy-Server).
myLocalApplication.com 172.89.23.777
(/) « The path gives info about the specific resource within the host that the Web client wants to access
(?) « An optional query is to pass a sequence of attribute–value pairs separated by a delimiter(&).
(#) « An optional fragment is often an id attribute of a specific element, and web browsers will scroll this element into view.
If parameter has an Epoch ?date=1467708674 then use.
var epochDate = 1467708674; var date = new Date( epochDate );
URL
Authentication url with username:password, If usernaem/password contains # symbol
like:
Username = `my_email#gmail`
Password = `Yash#777`
then You need to URL encode the # as %40. Refer...
http://my_email%40gmail.com:Yash%40777#www.my_site.com
encodeURI() (vs) encodeURIComponent() example
var testURL = "http:my_email#gmail:Yash777#//stackoverflow.com?tab=active&page=1#32942762";
var Uri = "/:#?&=,#", UriComponent = "$;+", Unescaped = "(-_.!~*')"; // Fixed
var encodeURI_Str = encodeURI(Uri) +' '+ encodeURI( UriComponent ) +' '+ encodeURI(Unescaped);
var encodeURIComponent_Str = encodeURIComponent( Uri ) +' '+ encodeURIComponent( UriComponent ) +' '+ encodeURIComponent( Unescaped );
console.log(encodeURI_Str, '\n', encodeURIComponent_Str);
/*
/:#?&=,# +$; (-_.!~*')
%2F%3A%40%3F%26%3D%2C%23 %2B%24%3B (-_.!~*')
*/
You can log window.location and see all the options, for just the URL use:
window.location.origin
for the whole path use:
window.location.href
there's also location.__
.host
.hostname
.protocol
.pathname
This will return the absolute URL of the current page using JavaScript/jQuery.
document.URL
$("*").context.baseURI
location.href
All browsers support Javascript window object. It defines the window of the browser.
The global objects and functions become part of the window object automatically.
All global variables are window objects properties and all global functions are its methods.
The whole HTML document is a window property too.
So you can use window.location object to get all url related attributes.
Javascript
console.log(window.location.host); //returns host
console.log(window.location.hostname); //returns hostname
console.log(window.location.pathname); //return path
console.log(window.location.href); //returns full current url
console.log(window.location.port); //returns the port
console.log(window.location.protocol) //returns the protocol
JQuery
console.log("host = "+$(location).attr('host'));
console.log("hostname = "+$(location).attr('hostname'));
console.log("pathname = "+$(location).attr('pathname'));
console.log("href = "+$(location).attr('href'));
console.log("port = "+$(location).attr('port'));
console.log("protocol = "+$(location).attr('protocol'));
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
I have this to strip out the GET variables.
var loc = window.location;
var currentURL = loc.protocol + '//' + loc.host + loc.pathname;
If there is someone who wants to concatenate the URL and hash tag, combine two functions:
var pathname = window.location.pathname + document.location.hash;
You can simply get your path using js itself, window.location or location will give you the object of current URL
console.log("Origin - ",location.origin);
console.log("Entire URL - ",location.href);
console.log("Path Beyond URL - ",location.pathname);
var currenturl = jQuery(location).attr('href');
Here is an example to get the current URL using jQuery and JavaScript:
$(document).ready(function() {
//jQuery
$(location).attr('href');
//Pure JavaScript
var pathname = window.location.pathname;
// To show it in an alert window
alert(window.location);
});
$.getJSON("idcheck.php?callback=?", { url:$(location).attr('href')}, function(json){
//alert(json.message);
});
To get the URL of the parent window from within an iframe:
$(window.parent.location).attr('href');
NB: only works on same domain
The following are examples of useful code snippets that can be used – some of the examples use standard JavaScript functions and are not specific to jQuery:
See 8 Useful jQuery Snippets For URL’s & Querystrings.
var path = location.pathname returns the path of the current URL (jQuery is not needed). The use of window.location is optional.
window.location will give you the current URL, and you can extract whatever you want from it...
If you want to get the path of the root site, use this:
$(location).attr('href').replace($(location).attr('pathname'),'');
Use window.location.href. This will give you the complete URL.
See purl.js. This will really help and can also be used, depending on jQuery. Use it like this:
$.url().param("yourparam");
By the following code you can get the current URL in Jquery.
$(location).attr('hostname'); //origin URL
$(location).attr('pathname'); // path name
$(location).attr('hash'); // everything comes after hash
Very Commonly Used top 3 ones are
1. window.location.hostname
2. window.location.href
3. window.location.pathname
var newURL = window.location.protocol + "//" + window.location.host + "/" + window.location.pathname;
// get current URL
$(location).attr('href');
var pathname = window.location.pathname;
alert(window.location);
Related
get the hostname(Base URL) using javascript
I get too many ways to get the hostname like code below: window.location.host // you'll get sub.domain.com:8080 or sub.domain.com:80 window.location.hostname // you'll get sub.domain.com window.location.protocol // you'll get http: window.location.port // you'll get 8080 or 80 window.location.pathname // you'll get /virtualPath In my case I want something different. For example: My QA site name is example.com/testsite/index.html My PROD site name is example.com/index.html The problem here using the above methods to get the hostname it is returning me only the hostname like this: example.com However for QA I need to return example.com/testsite For PROD i need to return example.com Is it possible with the single code? Thanks in advance.
To achieve what you require you'll need to check the window.location.hostname, and also the first folder in the window.location.pathname. Something like this: function getPath() { var folder = (window.location.pathname.split('/')[0] || '').toLowerCase() == 'testsite' ? '/testsite' : ''; return window.location.hostname + folder; }
Best method that works for both PROD & QA var BASE_URL = window.location.href; BASE_URL = BASE_URL.split("testsite"); if (BASE_URL.length > 1) { BASE_URL = BASE_URL[0]; BASE_URL = BASE_URL + 'testsite'; } else{ BASE_URL = window.location.origin; }
Use window.location.hostname; Example: Page URL is http://localhost:2239/Default2.aspx?id=5&name=SatinderSingh var getCurrentURL =window.location.href; //http://localhost:2239/Default2.aspx?id=5&name=SatinderSingh var getHostname=window.location.hostname; //localhost var getPathName=window.location.pathname // Default2.aspx var getPortNo=window.location.port // 2239 var getQueryString=window.location.search //?id=5&name=SatinderSingh var getHostname = window.location.hostname; //localhost var getPathName = window.location.pathname // Default2.aspx var split_PathName = String(getPathName.split("/")); var FinalURL = getHostname + "/" + split_PathName[1]
Access invocation URL in Swagger UI
In a custom JavaScript file in Swagger-UI I was trying to access the request URL because I needed to add it to a header before I submit the request. After looking at the source for swagger UI, I've not been able to figure out how to access the request URL. In a my custom JavaScript file I've cheated by stealing from the DOM using: (function() { $(function() { $(".submit").click(function (e) { // doesn't work // log(SwaggerUi.Views.OperationView.invocationUrl); var url = $($(this).parentsUntil(".operations")[3]).find(".path")[0].innerText; log("URL: " + url); }); }); })(); But being this is a hack, it will not work if the route had a parameter like so: url/{param}. To find the input param and replace would be another step I would rather not take. Am I missing some easy way that would allow me to access the request URL something along the lines of: SwaggerUi.requestUrl
Devised solution to traverse the DOM to get the information needed instead of using the information being stored by Swagger-UI. (note: using the embedded Swagger-UI given by Swashbuckle 5.4 your mileage may vary if you use a different version of Swagger-UI) $(".submit").click(function (e) { var originalUrl = $($(this).parentsUntil(".operations")[3]).find(".path")[0].innerText; log(originalUrl); var outputUrl = ""; $($(this).parentsUntil(".operations")[3]) .find("tbody.operation-params tr:contains('path')") .find("input") .each(function () { var pathParam = $(this).attr('name'); log(pathParam); var userInput = $(this).val(); log(userInput); outputUrl = originalUrl.replace("{" + pathParam + "}", userInput); log(outputUrl); }); // final requestUrl or invocationUrl var requestUrl = $(".footer h4").html().match(/: (\/[\w-]+)/)[1] + outputUrl; });
How get root url path
I'm searching a way to get the root URL of my Web project; as example: Local: http://localhost:52390/pages/user.aspx Expected result: http://localhost:52390 IIS: http://lst.pg.com/iLearn/pages/user.aspx Expected result: http://lst.pg.com/iLearn Exists a way to achieve this in ASPX? Or in Javascript/jQuery?
in javascript you can get url information from the location object. var href = location.href; //returns the entire url var host = location.hostname; //returns just the hostname of the url.
ASPX: Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath Implemented with Javascript: <script type="text/javascript"> var rootUrl = '<% =(Request.Url.GetLeftPart(UriPartial.Authority) + Request.ApplicationPath) %>'; </script>
There are times I need to get the rootpath from the code behind. Here is what I use. public static string GetRootPath() { HttpContext CTX; CTX = HttpContext.Current; return CTX.Request.ApplicationPath.ToString(); }
How can I extract and then change the url path using javascript?
I am trying to extract part of the url and replace it with custom text using javascript. For example, I want to fetch the current url such as: mydomain.com/url_part_to_change/some-other-stuff and then change that url to insert so that new new url is: mydomain.com/new_url_part/some-other-stuff Here is what I have: function changeURL() { var theURL = window.location.pathname; theURL.replace("/url_part_to_change/", "/new_url_part/"); //Set URL } However, when I try to call the function changeURL(), it returns undefined instead of the new url. For example if I do this: alert(changeURL()); then what alerts is undefined
TL;DR // update the pathname that will reload the page window.location.pathname = myNewPathname; Further Explanation: Window.location ( image attached below ) provides you an object containing all the uri parts information. So, you can get this object via window.location and access the property pathname then do your stuffs. For example: var locationObject = window.location; var pathnameToChange = locationObject.pathname; // do stuffs to "copy" of pathname, this will not reload the page var myNewPathname = doSomethingMyPathname( pathnameToChange ); Additional Examples: Alternatively, set new url using location.href. Check the MDN documentation for examples on location.assign(), location.replace(), location.reload() and notes on the different available functions // ie.myNewUrl is something I created -> www.blah.com/updated/path window.location.href = myNewUrl; // or window.location.assign(myNewUrl) A window.location Object in Console There are three references to further understand URI components URI_scheme Standards written by Tim Berners-Lee MDN Location Hope this helps.
This should work for you correctly: function changeURL() { // Get the url, just as you did var theURL = window.location.pathname; // Return the url return theURL.replace("/url_part_to_change/", "/new_url_part/"); }
you are not returning any thing in function, Please make function like function changeURL() { var theURL = window.location.pathname; return theURL.replace("/url_part_to_change/", "/new_url_part/"); //Set URL }
As the others said, you don't return anything. What they are forgetting is that String.replace() just makes a copy of theURL and doesn't change theURL. Try this: function changeURL() { var theURL = window.location.pathname; theURL = theURL.replace("/url_part_to_change/", "new_url_part/"); //Set URL return theURL; } alert(changeURL());
function changeURL() { //set new path window.location.pathname = "/new_url_part/"; //get new url const newURL = window.location.href; return newURL; }
You forgot to return function changeURL() { var theURL = window.location.pathname; var newURL = theURL.replace("/url_part_to_change/", "/new_url_part/"); //Set URL return newURL; } alert(changeURL())//Now you won't see undefined.
This is quite an old post but just to add: modifying window.location causes page navigations so if thats not desired create a new URL object and then you can modify the parts as needed. in my case i needed to change the path to a value from a value in the querystring. eg. /* * http://something.com/some/path?redirect=/some/other/path * -> * http://something.com/some/other/path */ let u = new URL(window.location.href) u.pathname=u.searchParams.get("redirect") u.searchParams.delete("redirect") console.log(u.href)
Modifying a query string without reloading the page
I am creating a photo gallery, and would like to be able to change the query string and title when the photos are browsed. The behavior I am looking for is often seen with some implementations of continuous/infinite page, where while you scroll down the query string keeps incrementing the page number (http://x.com?page=4) etc.. This should be simple in theory, but I would like something that is safe across major browsers. I found this great post, and was trying to follow the example with window.history.pushstate, but that doesn't seem to be working for me. And I'm not sure if it is ideal because I don't really care about modifying the browser history. I just want to be able to offer the ability to bookmark the currently viewed photo, without reloading the page every time the photo is changed. Here is an example of infinite page that modifies query string: http://tumbledry.org/ UPDATE found this method: window.location.href = window.location.href + '#abc';
If you are looking for Hash modification, your solution works ok. However, if you want to change the query, you can use the pushState, as you said. Here it is an example that might help you to implement it properly. I tested and it worked fine: if (history.pushState) { var newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?myNewUrlQuery=1'; window.history.pushState({path:newurl},'',newurl); } 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. And of course that it requires modern browsers that can process HTML5 History API. For more information: http://diveintohtml5.info/history.html https://developer.mozilla.org/en-US/docs/Web/Guide/API/DOM/Manipulating_the_browser_history
I want to improve Fabio's answer and create a function which adds custom key to the URL string without reloading the page. function insertUrlParam(key, value) { if (history.pushState) { let searchParams = new URLSearchParams(window.location.search); searchParams.set(key, value); let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + searchParams.toString(); window.history.pushState({path: newurl}, '', newurl); } } // to remove the specific key export function removeUrlParameter(paramKey) { const url = window.location.href console.log("url", url) var r = new URL(url) r.searchParams.delete(paramKey) const newUrl = r.href console.log("r.href", newUrl) window.history.pushState({ path: newUrl }, '', newUrl) }
Old question, modern answer to help future devs; using the URL interface: const url = new URL(window.location); url.searchParams.set('key', value); window.history.pushState(null, '', url.toString()); This makes sure you really only change the desired query-parameter.
Building off of Fabio's answer, I created two functions that will probably be useful for anyone stumbling upon this question. With these two functions, you can call insertParam() with a key and value as an argument. It will either add the URL parameter or, if a query param already exists with the same key, it will change that parameter to the new value: //function to remove query params from a URL function removeURLParameter(url, parameter) { //better to use l.search if you have a location/link object var urlparts= url.split('?'); if (urlparts.length>=2) { var prefix= encodeURIComponent(parameter)+'='; var pars= urlparts[1].split(/[&;]/g); //reverse iteration as may be destructive for (var i= pars.length; i-- > 0;) { //idiom for string.startsWith if (pars[i].lastIndexOf(prefix, 0) !== -1) { pars.splice(i, 1); } } url= urlparts[0] + (pars.length > 0 ? '?' + pars.join('&') : ""); return url; } else { return url; } } //function to add/update query params function insertParam(key, value) { if (history.pushState) { // var newurl = window.location.protocol + "//" + window.location.host + search.pathname + '?myNewUrlQuery=1'; var currentUrlWithOutHash = window.location.origin + window.location.pathname + window.location.search; var hash = window.location.hash //remove any param for the same key var currentUrlWithOutHash = removeURLParameter(currentUrlWithOutHash, key); //figure out if we need to add the param with a ? or a & var queryStart; if(currentUrlWithOutHash.indexOf('?') !== -1){ queryStart = '&'; } else { queryStart = '?'; } var newurl = currentUrlWithOutHash + queryStart + key + '=' + value + hash window.history.pushState({path:newurl},'',newurl); } }
I've used the following JavaScript library with great success: https://github.com/balupton/jquery-history It supports the HTML5 history API as well as a fallback method (using #) for older browsers. This library is essentially a polyfill around `history.pushState'.
If we simply want to update the query parameter without touching other parts of URL, there is no need to build the URL again. This is what I use: const addQueryParam = (key, value) => { const url = new URL(window.location.href); url.searchParams.set(key, value); window.history.pushState({}, '', url.toString()); }; const getQueryParam = (key) => { const url = new URL(window.location.href); return url.searchParams.get(key) || ''; };
Since everyone answering this seems to forget the hash, I want to add the code I'm using to keep all URL parameters: const urlParams = new URLSearchParams(window.location.search); /// Change some part of the URL params if (history.pushState) { const newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + "?" + urlParams.toString() + window.location.hash; window.history.replaceState({ path: newurl }, "", newurl); } else { window.location.search = urlParams.toString(); }
Then the history API is exactly what you are looking for. If you wish to support legacy browsers as well, then look for a library that falls back on manipulating the URL's hash tag if the browser doesn't provide the history API.
I thought I'd add a bit to Fabio and Aram's answers. I thought I might sometimes like to preserve the hash in the url. But usually not, so I set that parameter to default to false. replaceState still does not set the page title on Chrome. So I added a couple lines to change the title, if one is provided. function insertUrlParam(key, value, title = '', preserve_hash = false) { if (history.pushState) { let searchParams = new URLSearchParams(window.location.search); searchParams.set(key, value); let newurl = window.location.protocol + "//" + window.location.host + window.location.pathname + '?' + searchParams.toString(); if(preserve_hash) newurl = newurl + window.location.hash; let oldTitle = document.title; if(title !== '') { window.history.replaceState({path: newurl}, title, newurl); if(document.title !== title) { // fallback if above doesn't work document.title = title; } } else { // in case browsers ever clear titles set with empty string window.history.replaceState({path: newurl}, oldTitle, newurl); } } }