Created
March 19, 2025 06:38
-
-
Save symbioticstar/60daec8cd1bf5a8f6e5598e36223a690 to your computer and use it in GitHub Desktop.
remove spm
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function modifyPage() { | |
let forEach = Function.call.bind([].forEach); | |
let removeSpm = (url, next) => { | |
let search = url.search; | |
if (!search) return; | |
let query = parseQuery(search.slice(1)); | |
if (query.spm) { | |
delete query.spm; | |
let param = toParam(query); | |
next(url.origin + url.pathname + (param ? "?" + param : "") + url.hash); | |
} | |
}; | |
let parseQuery = (param) => { | |
return param | |
.split("&") | |
.map((pair) => pair.split("=")) | |
.reduce((o, p) => { | |
o[p[0]] = decodeURIComponent(p[1]); | |
return o; | |
}, {}); | |
}; | |
let toParam = (object) => { | |
return Object.keys(object) | |
.map((key) => key + "=" + encodeURIComponent(object[key])) | |
.join("&"); | |
}; | |
let removeLinkSpm = (link) => { | |
removeSpm(link, (newUrl) => { | |
link.href = newUrl; | |
}); | |
}; | |
let removeLocationSpm = () => { | |
removeSpm(location, (newUrl) => { | |
history.replaceState(null, document.title, newUrl); | |
}); | |
}; | |
let isLink = (node) => { | |
return node && node.nodeName === "A"; | |
}; | |
let observer = new MutationObserver((mutations) => { | |
mutations.forEach((mutation) => { | |
let type = mutation.type; | |
if (type === "attributes") { | |
if (mutation.attributeName === "href" && isLink(mutation.target)) { | |
removeLinkSpm(mutation.target); | |
} | |
} else if (type === "childList" || type === "subtree") { | |
forEach(mutation.addedNodes, (node) => { | |
if (isLink(node)) { | |
removeLinkSpm(node); | |
} | |
}); | |
} | |
}); | |
}); | |
observer.observe(document.body, { | |
attributes: true, | |
childList: true, | |
subtree: true, | |
}); | |
forEach(document.links, removeLinkSpm); | |
removeLocationSpm(); | |
} | |
modifyPage() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment