크롬을 쓰고 여러 개의 화면을 쓰다 보니 동일한 중복탭이 많이 생기고 가끔 렉이 걸리는 경우가 발생했다. 동일한 중복탭이 생겼을 때 하나를 남기고 모두 닫는 확장 프로그램을 만들었다. 사람들에게 공유하기 위해서는 5$를 내야 하기에 나는 그렇게 하고 싶지는 않기 때문에 그냥 코드를 공유한다. 

 

우선 js를 사용해야 하고, 로직 자체는 아래와 같다. 

 

1. 탭에서 검색했을 때 기존  탭들과 url과 id 비교

2. 같은 url이 존재할 경우 모달을 띄우고 닫을 지 말지 확인

3. 닫기 할 경우 가장 최근의 탭을 제외하고 모두 닫기 

 

코드 구현은 모달 때문에 2개의 js 파일이 필요하고 우선 현재 열린 탭들의 url을 확인하는 것은 아래와 같다.

chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete' && tab.active) {
if (!tab.url || tab.url === 'chrome://newtab/' || tab.url === 'about:blank') {
return; // 빈 탭인 경우 종료
}
chrome.tabs.query({}, (tabs) => {
const url = tab.url;
const duplicateTabs = tabs.filter(t => t.url === url && t.id !== tabId);
if (duplicateTabs.length > 0) {
chrome.tabs.sendMessage(tabId, { action: "showModal", duplicates: duplicateTabs });
}
});
}
});
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "removeTab") {
chrome.tabs.remove(request.id, (result) => {
if (chrome.runtime.lastError) {
console.error("Error removing tab:", chrome.runtime.lastError);
}
});
}
});

 

여기서 그냥 탭을 열었을 때와 url이 없을 때는 밑을 진행하지 않기 위해서 return;으로 끝낸다. 

그 외에 경우에는 기존 탭들과 연 탭의 url과 id를 비교하고, 존재할 경우 sendMessage showModal 메시지를 보낸다.  

chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "showModal") {
createModal(request.duplicates);
}
if (request.action === "removeTab") {
chrome.tabs.remove(request.id, (result) => {
if (chrome.runtime.lastError) {
console.error("Error removing tab:", chrome.runtime.lastError);
} else {
console.log(`Tab with id ${request.id} removed successfully.`);
}
});
}
});
// 모달 생성 함수
function createModal(duplicates) {
// 기존 모달 제거 (중복 방지)
const existingModal = document.getElementById("duplicate-tab-modal");
if (existingModal) {
existingModal.remove();
}
// css 생략
// 모달 메시지
const message = document.createElement("p");
message.textContent = "중복된 탭이 발견되었습니다. 하나를 남기고 모두 닫으시겠습니까?";
message.style.marginBottom = "20px";
// '모두 닫기' 버튼
const closeButton = document.createElement("button");
closeButton.onclick = () => {
console.log("Close button clicked");
duplicates.forEach(t => {
if (t && t.id) {
chrome.runtime.sendMessage({ action: "removeTab", id: t.id });
}
});
removeModal(); // 모달 제거
};
// '취소' 버튼
const cancelButton = document.createElement("button");
cancelButton.onclick = () => {
console.log("Cancel button clicked");
removeModal(); // 모달 제거
};
buttonContainer.appendChild(closeButton);
buttonContainer.appendChild(cancelButton);
modal.appendChild(message);
modal.appendChild(buttonContainer);
document.body.appendChild(overlay);
document.body.appendChild(modal);
}
// 모달 제거 함수
const removeModal = () => {
const modalElement = document.getElementById("duplicate-tab-modal");
const overlayElement = document.getElementById("duplicate-tab-overlay");
if (modalElement) {
modalElement.remove();
}
if (overlayElement) {
overlayElement.remove();
}
};

 

모달을 띄운 후 모달 실행 시 넘긴 tab.id를 제외 하고 removeTab sendMessage를 실행시키면 background.js에서 메시지를 받아 모두 닫는 것을 실행한다. 그 후 모달 제거만 호출해 주면 완성된다. 이제 두 js파일과 확장프로그램 이미지파일, manifest.json을 한 곳에 모아서 올려주면 끝난다. 

 

manifest.json은 다음과 같다. 

{
"manifest_version": 3,
"name": "중복 탭 정리",
"version": "1.0",
"description": "중복된 탭을 자동으로 감지하고 정리하는 크롬 확장 프로그램",
"permissions": ["tabs"],
"background": {
"service_worker": "background.js"
},
"content_scripts": [
{
"matches": ["<all_urls>"],
"js": ["content.js"]
}
],
"icons": {
"16": "check-v.png",
"48": "check-v.png",
"128": "check-v.png"
}
}

 

이제 계정 옆에 확장자를 클릭하고 확장자 프로그램 관리 -> 압축해제된 확장 프로그램을 로드합니다. 를 누른 후 파일들이 존재한 폴더를 선택해주면 끝난다. 실제 동작은 이렇게 된다.