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