get-apex-domain
Version:
Returns the apex domain (aka base, bare, naked, root apex, or zone apex domain) of the current web page without the use of a public suffix list. The apex domain is also the top-most domain that allows for setting cookies.
44 lines (35 loc) • 1.26 kB
JavaScript
Object.defineProperty(exports, "__esModule", {
value: true
});
exports["default"] = void 0;
var cookieToken = "__apex_test__";
var getLastArrayItems = function getLastArrayItems(arr, itemCount) {
return arr.slice(-itemCount);
};
/**
* Retrieves the apex domain.
* @param {Object} window The browser's window object
* @param {Object} cookieJar An object with get, set, and remove methods
* for cookie manipulation.
* @returns {string} The apex domain.
*/
var _default = function _default(window, cookieJar) {
if (!window.navigator.cookieEnabled) {
throw new Error("Unable to detect apex domain without cookies enabled.");
}
var domain = "";
var hostname = window.location.hostname;
var hostParts = hostname.toLowerCase().split(".");
for (var i = 1; i < hostParts.length + 1; i++) {
domain = getLastArrayItems(hostParts, i).join(".");
cookieJar.set(cookieToken, cookieToken, ".".concat(domain));
if (cookieJar.get(cookieToken)) {
cookieJar.remove(cookieToken, ".".concat(domain));
return domain;
}
} // If we get to this point, it's likely the hostname is
// "localhost", which is a reserved top-level domain name.
};
exports["default"] = _default;
module.exports = exports.default;
;