Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get The Current Domain Name With Javascript (Not the path, etc.)

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.

like image 547
Freesnöw Avatar asked Jul 09 '12 19:07

Freesnöw


People also ask

What is domain in JavaScript?

Definition and Usage. The domain property returns the domain name of the server (the document was loaded from). The domain property returns null if the document was created in memory.

How do I get a domain name in react?

To access the domain name from an above URL, we can use the window. location object that contains a hostname property which is holding the domain name. Similarly, we can also use the document. domain property to access it.


2 Answers

How about:

window.location.hostname 

The location object actually has a number of attributes referring to different parts of the URL

like image 71
Gareth Avatar answered Sep 20 '22 13:09

Gareth


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 
like image 39
Sunil Shakya Avatar answered Sep 19 '22 13:09

Sunil Shakya