Skip to content

Instantly share code, notes, and snippets.

@azu
Last active June 24, 2021 03:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save azu/da9c9167d7fd1270c7970ba2a9aaad50 to your computer and use it in GitHub Desktop.
Save azu/da9c9167d7fd1270c7970ba2a9aaad50 to your computer and use it in GitHub Desktop.
Get domain(site) from url using document.cookie hacking. without public suffix
const isSite = (domain) => {
console.log(domain)
const key = "WILL_BE_FIRED." + 'xxxx-xxxx-xxx-xxxx'.replace(/[x]/g, (c) => {
const r = Math.floor(Math.random() * 16);
return r.toString(16);
});
document.cookie = `${key}=1; domain=${domain}; samesite`;
// Test wrinting
console.log("document.cookie", document.cookie)
const canWrite = document.cookie.includes(`${key}=1`);
console.log("canWrite", canWrite);
// - [ ] More clear
document.cookie = `${key}=; max-age=0`
return canWrite;
};
const getSite = (urlString) => {
const url = new URL(urlString);
const parts = url.host.split(".").reverse();
let testDomain = parts.shift(); // Why does "org" can write?
for (const part of parts) {
testDomain = testDomain ? part + "." + testDomain : part;
if (isSite(testDomain)) {
return testDomain
}
}
throw new Error("No domain");
}
// Should call this in the site
const site = getSite(location.href);
console.log("site: ", site);
// https://azu.github.io/ → azu.github.io
// https://en.wikipedia.org → wikipedia.org
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment