IT

Javascript를 사용하여 현재 도메인 이름 가져 오기 (경로 등이 아님)

lottoking 2020. 5. 12. 08:23
반응형

Javascript를 사용하여 현재 도메인 이름 가져 오기 (경로 등이 아님)


같은 사이트에 두 개의 도메인 이름을 구매할 계획입니다. 사용되는 도메인에 따라 페이지에서 약간 다른 데이터를 제공 할 계획입니다. 내 페이지를로드하는 실제 도메인 이름을 감지하여 내용을 어떻게 변경해야하는지 알 수있는 방법이 있습니까?

나는 이런 것들을 둘러 보았지만 대부분 내가 원하는 방식으로 작동하지 않습니다.

예를 들어

document.write(document.location)

JSFiddle 그것은 반환

http://fiddle.jshell.net/_display/

즉 실제 경로 또는 그 무엇이든.


어때요?

window.location.hostname

location객체는 실제로이 속성의 수 URL의 다른 부분을 언급을


스크립트에서 실행하십시오 : 경로 : http : // localhost : 4200 / landing? query = 1 # 2

console.log(window.location.hash)

위치는 다음 값을 갖습니다.

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"

호스트 이름 (예 :)이 아닌 www.beta.example.com도메인 이름 (예 example.com:)에 관심이있는 경우 유효한 호스트 이름에 대해 작동합니다.

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;
}

  • 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); // ..

이전 버전은 전체 도메인 (하위 도메인 포함)을 가져 왔습니다. 이제 선호도에 따라 올바른 도메인을 결정합니다. 따라서 두 번째 인수가 true로 제공되면 하위 도메인이 포함되고 그렇지 않으면 '주 도메인'만 반환합니다


Javascript의 위치 객체에서 쉽게 얻을 수 있습니다.

예를 들어이 페이지의 URL은 다음과 같습니다.

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"

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.


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 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

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);

for my case the best match is window.location.origin


I figure it ought to be as simple as this:

url.split("/")[2]


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


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.

참고URL : https://stackoverflow.com/questions/11401897/get-the-current-domain-name-with-javascript-not-the-path-etc

반응형