I want to get the base path of my Angular app.
Right now I'm doing this: $scope.baseUrl = '$location.host()
But I only get this: /localhost. My current baseURL is http://localhost:9000/.
An alternative answer is using the $window service in conjunction with $location.absUrl() to create a new URL object, and then grab the origin via the origin property. This will give you exactly what you're looking for (minus the trailing '/').
$scope.baseUrl = new $window.URL($location.absUrl()).origin; will give you back http://localhost:9000 in your case.
Try this: $location.$$absUrl
console.log('$location',$location.$$absUrl);
btw /localhost is your base path, but I guess you meant entire URL.
To get just the baseurl and nothing else use
$browser.baseHref()
it will return something like
/central/
A cross browser solution that worked for me was:
$location.$$absUrl.replace($location.$$url, '')
$$absUrl is the entire url (e.g. https://google.com/search/spiders)
$$url is the part after the host (e.g. /search/spiders)
Modify to taste.
try injecting $location it has an absUrl() method on it that will return the entire current url
https://docs.angularjs.org/api/ng/service/$location
If you only want to get the base url of the site, and not the current url of the page, e.g. from https://www.google.com/somewhere/in-the-middle-of-nowhere you want to get https://www.google.com, then simply do:
// For www.google.com
$scope.baseUrl = $locaton.$$host;
// For https://www.google.com
$scope.baseUrl = $location.$$protocol + '://' + $location.$$host;
Instead of using $scope.baseUrl = '$location.host()
Use this one :-
$scope.baseUrl = $location.absUrl();
I am late for the party, however I think location.pathname can be better.
Related
I am looking for plain JavaScript code (no jQuery etc.) to learn the directory path component of my currently loaded page's URL.
For instance, if my page is loaded as "http://localhost/myapp/index.html", I like to end up with "http://localhost/myapp/".
I need this in order to create the path to a different file in the same location, e.g. to "http://localhost/myapp/other.html".
It looks like this does the trick:
var href = window.location.href;
var dir = href.substring(0, href.lastIndexOf('/')) + "/";
Is this a safe method or can this fail with more complex URLs?
Highlighting the comment in the question that helped me:
Phylogenesis's comment:
The simple solution is location.href.replace(/[^/]*$/, ''); then.
One more option to consider, which has the benefit that any query string will not be an issue since window.location.pathname does not pick up the query string.
window.location.origin + window.location.pathname.slice(0, window.location.pathname.lastIndexOf('/'))
A better solution would be
location.href.replace(/\/[^\/]+?\.[^\/]+?$/, '/')
I know how to go to link / url / address, like;
window.location = "www.example.com/index.html";
or
document.location.href="www.example.com/index.html";
But suppose I want to navigate from index1.html to index2.html, how can i achieve this without providing the www.example.com/ prefix? Please don't suggest that I set www.example.com/ in a global variable / constant. The address may change to www.example2.com/subfolder1/subfolder2/ to www.examplea.com/.... The mentioned methods works only in the case of root pages. I mean, providing document.location.href="index.html"; will navigate the browser to rootdomain/index.html, even if I am staying in rootdomain/section1/section2/somepage.html. But I want to navigate to rootdomain/section1/section2/index.html
How can I achieve this by providing just the page name?
If you have a / at the beginning of your string, it'll go to the local page:
window.location = "/index.html"
Just like you would do otherwise, but using the relative path:
document.location.href = '/index2.html'; //relative path
window.location.pathname = 'index2.html';
You can also just use relative urls on the document.location.href.
What might be even better is window.location.assign('index2.html');. This is especially useful when you're at www.example.com/foo/.../index1.html and don't want to specify the whole path to get to www.example.com/foo/.../index2.html.
For more options, see https://developer.mozilla.org/en-US/docs/DOM/window.location .
I plan on buying two domain names for the same site. Depending on which domain is used I plan on providing slightly different data on the page. Is there a way for me to detect the actual domain name that the page is loading from so that I know what to change my content to?
I've looked around for stuff like this but most of it doesn't work the way I want it to.
For instance when using
document.write(document.location)
on JSFiddle it returns
http://fiddle.jshell.net/_display/
i.e. the actual path or whatever that is.
How about:
window.location.hostname
The location object actually has a number of attributes referring to different parts of the URL
Let's suppose you have this url path:
http://localhost:4200/landing?query=1#2
So, you can serve yourself by the location values, as follow:
window.location.hash: "#2"
window.location.host: "localhost:4200"
window.location.hostname: "localhost"
window.location.href: "http://localhost:4200/landing?query=1#2"
window.location.origin: "http://localhost:4200"
window.location.pathname: "/landing"
window.location.port: "4200"
window.location.protocol: "http:"
window.location.search: "?query=1"
Now we can conclude you're looking for:
window.location.hostname
If you are not interested in the host name (for example www.beta.example.com) but in the domain name (for example example.com), this works for valid host names:
function getDomainName(hostName)
{
return hostName.substring(hostName.lastIndexOf(".", hostName.lastIndexOf(".") - 1) + 1);
}
function getDomain(url, subdomain) {
subdomain = subdomain || false;
url = url.replace(/(https?:\/\/)?(www.)?/i, '');
if (!subdomain) {
url = url.split('.');
url = url.slice(url.length - 2).join('.');
}
if (url.indexOf('/') !== -1) {
return url.split('/')[0];
}
return url;
}
Examples
getDomain('http://www.example.com'); // example.com
getDomain('www.example.com'); // example.com
getDomain('http://blog.example.com', true); // blog.example.com
getDomain(location.href); // ..
Previous version was getting full domain (including subdomain). Now it determines the right domain depending on preference. So that when a 2nd argument is provided as true it will include the subdomain, otherwise it returns only the 'main domain'
If you wish a full domain origin, you can use this:
document.location.origin
And if you wish to get only the domain, use can you just this:
document.location.hostname
But you have other options, take a look at the properties in:
document.location
You can get it from location object in Javascript easily:
For example URL of this page is:
http://www.stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc
Then we can get the exact domain with following properties of location object:
location.host = "www.stackoverflow.com"
location.protocol= "http:"
you can make the full domain with:
location.protocol + "//" + location.host
Which in this example returns http://www.stackoverflow.com
I addition of this we can get full URL and also the path with other properties of location object:
location.href= "http://www.stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc"
location.pathname= "questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc"
window.location.hostname is a good start. But it includes sub-domains, which you probably want to remove. E.g. if the hostname is www.example.com, you probably want just the example.com bit.
There are, as ever, corner cases that make this fiddly, e.g. bbc.co.uk. The following regex works well for me:
let hostname = window.location.hostname;
// remove any subdomains, e.g. www.example.com -> example.com
let domain = hostname.match(/^(?:.*?\.)?([a-zA-Z0-9\-_]{3,}\.(?:\w{2,8}|\w{2,4}\.\w{2,4}))$/)[1];
console.log("domain: ", domain);
Since this question asks for domain name, not host name, a correct answer should be
window.location.hostname.split('.').slice(-2).join('.')
This works for host names like www.example.com too.
If you are only interested in the domain name and want to ignore the subdomain then you need to parse it out of host and hostname.
The following code does this:
var firstDot = window.location.hostname.indexOf('.');
var tld = ".net";
var isSubdomain = firstDot < window.location.hostname.indexOf(tld);
var domain;
if (isSubdomain) {
domain = window.location.hostname.substring(firstDot == -1 ? 0 : firstDot + 1);
}
else {
domain = window.location.hostname;
}
http://jsfiddle.net/5U366/4/
Use
document.write(document.location.hostname)
window.location has a bunch of properties. See here for a list of them.
I figure it ought to be as simple as this:
url.split("/")[2]
If you want to get domain name in JavaScript, just use the following code:
var domain_name = document.location.hostname;
alert(domain_name);
If you need to web page URL path so you can access web URL path use this example:
var url = document.URL;
alert(url);
What about this function?
window.location.hostname.match(/\w*\.\w*$/gi)[0]
This will match only the domain name regardless if its a subdomain or a main domain
for my case the best match is window.location.origin
Combining a few answers from the above, the following works really well for me for destroying Cookies:
/**
* Utility method to obtain the domain URI:
*/
fetchDomainURI() {
if (window.location.port.length > 0) {
return window.location.hostname;
}
return `.${window.location.hostname.match(/\w*\.\w*$/gi)[0]}`;
}
Works for IP addresses with ports, e.g., 0.0.0.0:8000 etc, as well as complex domains like app.staging.example.com returning .example.com => allows for cross-domain Cookie setting and destroying.
I'm new to JavaScript, but cant you just use: document.domain ?
Example:
<p id="ourdomain"></p>
<script>
var domainstring = document.domain;
document.getElementById("ourdomain").innerHTML = (domainstring);
</script>
Output:
domain.com
or
www.domain.com
Depending on what you use on your website.
Even if the question is about the domain name, the accepted solution includes the subdomain (eg. you get blog.example.com calling location.hostname).
For future reference I suggest a one-liner to extract only the domain (eg. https://blog.example.com/index.html -> example.com) as Micheal.
location.hostname.split('.').filter(( _, i) => i < 2).join('.')
Beware! It can break when the TLD is composed of two parts (eg. .co.uk). If that's your case change 2 with 3 in the code above.
you can use this to do away with the port number.
var hostname = window.location.host;
var urlWithoutPort = `https://${hostname}`;
console.log(urlWithoutPort);
https://publicsuffix.org/list/
(https://github.com/publicsuffix/list/blob/master/public_suffix_list.dat)
is needed to correctly parse out all domains without suffixes, working with dots as in the answers above will never completely be correct. Feel free to run the above codes samples against the public suffixes dat file to realize this.
You can roll your own code based on this or use a package like https://www.npmjs.com/package/tldts
getDomainWithoutSuffix('google.com'); // returns `google`
getDomainWithoutSuffix('fr.google.com'); // returns `google`
getDomainWithoutSuffix('fr.google.google'); // returns `google`
getDomainWithoutSuffix('foo.google.co.uk'); // returns `google`
getDomainWithoutSuffix('t.co'); // returns `t`
getDomainWithoutSuffix('fr.t.co'); // returns `t`
getDomainWithoutSuffix('https://user:password#example.co.uk:8080/some/path?and&query#hash'); // returns `example`
I am trying to redirect to a different page in IE9 (9.0.3).
When I try to get/set document.location, or document.location.href, or window.location/window.location.href, I'm unable to do so. It fails without giving any errors.
I've tried to check whether the document and windows objects are set, and they are, so I have no idea why the location object is "missing".
I tried getting the document.URL and that works fine, but it's read-only.
Anyone know what the problem is or how to achieve this in a cross-browser way?
I was also experiencing the same problem but found that adding
window.event.returnValue = false;
above line in the javascript before the redirection resolved the problem.
See this: http://social.msdn.microsoft.com/Forums/en/iewebdevelopment/thread/c864ae63-66f6-4656-bcae-86b0018d70c9
Apparently it's a caching bug, you can solve it by appending a timestamp to the destination URL (that is, using a "unique" URL every time).
Perhaps your IE9 has some security restrictions in place that prevent JavaScript from directing URL's. window.location.href = "" should work normally on IE9.
Cache may be the reason, try:
location.href='something.php?tmp=' + Date.parse(new Date())
Hope it helps
You should use an absolute URL:
var url = '/section/page/';
var host = window.location.hostname;
window.location = 'http://' + host + url;
Where url is the relative path to your page.
If I have a hostname such as: http://sample.example.com and in Javascript I do window.location.hostname, would I get "example.com" or "sample.example.com"?
If not, how would I be able to get sample.example.com?
Yes, window.location.hostname will give you subdomains as well. If this isn't working, or isn't supported by some other browser, you could quite easily parse for it:
// window.location.href == "http://sample.somedomain.com/somedir/somepage.html"
var domain = /:\/\/([^\/]+)/.exec(window.location.href)[1];
This does the trick for me:
var host = window.location.host
var subdomain = host.split('.')[0]
I know this is an old question but a more robust answer would be to capture all subdomains. It's possible to have nested subdomains such as https://my.company.website.com. In order to adequately capture all subdomains, I think this is the simplest answer:
// for https://my.company.website.com,
const subdomain = window.location.hostname.split('.').slice(0, -2).join('.');
console.log(subdomain); // "my.company"
It can be done as below:
var subdomain = window.location.host.split('.')[1] ? window.location.host.split('.')[0] : false;
First of all, it's window.location, not document.location (document.location works in some browsers but it is not standard)
And yes, location.hostname will return the entire domain name, including any subdomains
Read more here
Window Location
const subdomain = window.location.hostname.split(".")[0]
window.location.hostname return string include subdomain - main domain - ltd
so you can easily get the first word by converting it to an array then getting first item
Yes alert(window.location.hostname) will include subdomains like 'www' and 'sample'.
How about this snippet. It might help:
var a = new String(window.location);
a = a.replace('http://','');
a = a.substring(0, a.indexOf('/'));
alert(a);
with array destructuring you can do this:
// window.location.host = "meta.stackoverflow.com"
const [ , , subdomain] = window.location.hostname.split(".").reverse();
// console.log(subdomain);
// "meta"
I recommend using the npm package psl (Public Suffix List). You can look this link: npm psl
It's a simple way to split domain parts like subdomain.maindomain.extension
// Print Subdomain
console.log(window.location.host.split('.')[0]);
// Print Maindomain
console.log(window.location.host.split('.')[1]);
// Print extension
console.log(window.location.host.split('.')[2]);
I recommend you reference this helpful cheatsheet.
source: https://www.samanthaming.com/tidbits/86-window-location-cheatsheet/