How to get base domain from the URL in JavaScript

后端 未结 9 563
萌比男神i
萌比男神i 2020-12-06 02:52

I would like to extract the base domain from the url in javascript. For example for the list of urls listed below I need to get google.com (or googl

9条回答
  •  孤街浪徒
    2020-12-06 03:40

    It loops through the parts of a full hostname and tries to set a cookie on that domain, it will set a cookie at the highest level possible. This function is helpful if you are trying to set the cookie in the base domain

    Note: test this code in the respective website browser console, otherwise doesn't work.

    function getDomain () {
            var domain =document.domain;
            var i = 0;
            var parts = domain.split('.');
            var value = 'km_' + (new Date()).getTime();
            while (i < (parts.length - 1) && document.cookie.indexOf(value + '=' + value) == -1) {
                domain = parts.slice(-1 - (++i)).join('.');
                document.cookie = value + "=" + value + ";domain=" + domain + ";";
            }
            document.cookie = value + "=;expires=Thu, 01 Jan 1970 00:00:01 GMT;domain=" + domain + ";";
            return domain
    }
    

提交回复
热议问题