Getting domain name from javascript is simple. You can get domain name from [cci]window.location.hostname[/cci] variable.

[sourcecode lang=”javascript”]
var hostname = window.location.hostname;
alert(hostname);
[/sourcecode]

Click following button to test above code.

Get full domain name

Domain name you got this way is simply domain name in browser address bar. Sometimes address bar you got not include [cci]http://[/cci] or [cci]www[/cci] prefix. To make sure you get the full domain name, you must check it first.

[sourcecode lang=”javascript”]
var hostname = window.location.hostname;
hostname = (hostname.indexOf(‘www.’)!=-1?hostname:’www.’+hostname);
hostname = (hostname.indexOf(‘http’)!=-1?hostname:’http://’+hostname);
alert(hostname);
[/sourcecode]

Click button belo to try above code:


0 Comments

Leave a Reply

Avatar placeholder