Skip to content

Instantly share code, notes, and snippets.

@santaklouse
Created February 6, 2025 20:52
Show Gist options
  • Save santaklouse/e2b17664e7be227c1ca99ebf0ec424e6 to your computer and use it in GitHub Desktop.
Save santaklouse/e2b17664e7be227c1ca99ebf0ec424e6 to your computer and use it in GitHub Desktop.
remove chrome tab duplicates
// Utils
const parseUrl = (url, options) => {
const { origin, hash, search } = url
const pathname = url.pathname.replace(/\/index\.(x?html?|php|cgi|aspx)$/, "/")
return {
origin,
hash: options?.ignoreHash ? "" : hash,
search: options?.ignoreQuery ? "" : search,
pathname: options?.ignorePathname ? "" : pathname
}
}
const getUrl = (url, options) => {
if (!url) {
return null
}
if (
url.startsWith("chrome-extension://") &&
url.includes("/html/suspended.html#")
) {
const paramsString = url.split("suspended.html#")[1]
const searchParams = new URLSearchParams(paramsString)
const params = Object.fromEntries(Array.from(searchParams))
if (params.uri) {
url = params.uri
}
}
const { origin, pathname, search, hash } = parseUrl(new URL(url), options)
return `${origin}${pathname}${search}${hash}`
}
const getCurrentTab = async () =>
(await chrome.tabs.query({ active: true, currentWindow: true }))[0]
// Tasks
const removeDuplicatedTabs = async (tabs, options) => {
const currentTab = await getCurrentTab()
const currentUrl = getUrl(currentTab.url, options)
const checkedUrl = new Set()
if (currentUrl) {
checkedUrl.add(currentUrl)
}
const targetTabIdList = tabs
.filter(tab => {
const { id } = tab
const url = getUrl(tab.url, options)
if (!url || typeof id !== "number") {
return false
}
if (checkedUrl.has(url) && currentTab.id !== id) {
return true
}
checkedUrl.add(url)
return false
})
.map(({ id }) => id)
console.log(`targetTabIdList: ${targetTabIdList}`)
for (const id of targetTabIdList) {
chrome.tabs.get(id, tab => {
console.log(
`%s${tab.id}:${tab.title} - ${getUrl(tab.url)}`,
"background-color:grey"
)
})
//chrome.tabs.remove(id);
}
}
var main = async options => {
const currentWindow = !Boolean(options?.includeAllWindow) ? true : undefined
const pinned = Boolean(options?.includePinnedTabs) ? undefined : false
const tabs = await chrome.tabs.query({
windowType: "normal",
currentWindow,
pinned
})
removeDuplicatedTabs(tabs, options)
}
main({ includePinnedTabs: true, includeAllWindow: false }).then(
console.log("Done!")
)
@santaklouse
Copy link
Author

need to run from context of any extension that has access to tabs permission

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment