Hi there! I'm currently developing a chrome extension similar to "OneTab" and "Better OneTab". I want you to understand the source code of the extension and help me make changes to it. Here is the code:
"""background.js
// Function to generate a unique ID
function generateUUID() {
return crypto.randomUUID();
}
// Open extension page when its icon is clicked
chrome.action.onClicked.addListener(() => {
chrome.tabs.create({ url: 'tabs.html' });
});
// Create context menu items when the extension is installed or updated
chrome.runtime.onInstalled.addListener(() => {
// Menu items
chrome.contextMenus.create({
id: 'saveTabsOnLeft',
title: 'Save tabs on the left',
contexts: ['action']
});
chrome.contextMenus.create({
id: 'saveTabsOnRight',
title: 'Save tabs on the right',
contexts: ['action']
});
chrome.contextMenus.create({
id: 'saveAllTabs',
title: 'Save all tabs',
contexts: ['action']
});
chrome.contextMenus.create({
id: 'saveOnlyThisTab',
title: 'Save only this tab',
contexts: ['action']
});
});
// Listen for clicks on context menu items
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId === 'saveTabsOnLeft') {
saveTabsOnLeft(tab);
} else if (info.menuItemId === 'saveTabsOnRight') {
saveTabsOnRight(tab);
} else if (info.menuItemId === 'saveAllTabs') {
saveAllTabs(tab);
} else if (info.menuItemId === 'saveAllTabsExceptThis') {
saveAllTabsExceptThis(tab);
} else if (info.menuItemId === 'saveOnlyThisTab') {
saveOnlyThisTab(tab);
}
});
// Function to save tabs on the left
function saveTabsOnLeft(currentTab) {
chrome.tabs.query({ currentWindow: true }, (tabs) => {
saveTabs(tabs.filter(tab => (tab.index < currentTab.index) && (!tab.pinned) && tab.url.startsWith('http')));
});
}
// Function to save tabs on the right
function saveTabsOnRight(currentTab) {
chrome.tabs.query({ currentWindow: true }, (tabs) => {
saveTabs(tabs.filter(tab => (tab.index > currentTab.index) && (!tab.pinned) && tab.url.startsWith('http')));
});
}
// Function to save all tabs
function saveAllTabs(currentTab) {
chrome.tabs.query({ currentWindow: true }, (tabs) => {
saveTabs(tabs.filter(tab => (!tab.pinned) && tab.url.startsWith('http')));
});
}
// Function to save all tabs except current
function saveAllTabsExceptThis(currentTab) {
chrome.tabs.query({ currentWindow: true }, (tabs) => {
saveTabs(tabs.filter(tab => (tab.id !== currentTab.id) && (!tab.pinned) && tab.url.startsWith('http')));
});
}
Assistant
// Function to save only the current tab
function saveOnlyThisTab(currentTab) {
if((!currentTab.pinned) && currentTab.url.startsWith('http')) {
saveTabs([currentTab]);
}
}
// Generic function to save tabs
function saveTabs(tabs) {
// Check if there are any tabs to save
if (tabs.length === 0) {
console.log('No tabs to save');
return;
}
// Map the filtered tabs to get their title and URL
const tabsData = tabs.map(tab => ({
id: generateUUID(),
title: tab.title,
url: tab.url
}));
// Retrieve saved tab groups to determine the default category name and save it
chrome.storage.local.get('savedTabGroups', (data) => {
let savedTabGroups = data.savedTabGroups || [];
// Generate default category name as 'Book X'
let groupNumber = savedTabGroups.length + 1;
let defaultCategoryName = 'Book ' + groupNumber;
// Ensure the category name is unique (deprecated)
/*
while (savedTabGroups.some(group => group.category === defaultCategoryName)) {
groupNumber++;
defaultCategoryName = 'Book ' + groupNumber;
}
*/
// Add the new group to the start of the array
savedTabGroups.unshift({
id: generateUUID(),
category: defaultCategoryName,
tabs: tabsData,
collapsed: false
});
// Save the updated tab groups to storage
chrome.storage.local.set({ 'savedTabGroups': savedTabGroups }, () => {
console.log(`${tabs.length} tab(s) saved under "${defaultCategoryName}"`);
// Close the saved tabs
const tabIdsToClose = tabs.map(tab => tab.id);
chrome.tabs.remove(tabIdsToClose);
// Send a message to tabs.html to refresh the tab groups
chrome.runtime.sendMessage({ action: 'tabs_saved' });
});
});
}
"""
"""tabs.html
<!-- Main Content -->
<div id="mainContent">
<!-- Tabs Content -->
<div id="tabsContent">
<p id="resultMessage">Loading saved data...</p>
<!-- Tab Groups will be displayed here -->
<div id="tabGroups"></div>
</div>
<!-- Settings Content (Initially Hidden) -->
<div id="settingsContent" style="display: none;">
<h2>Settings</h2>
<!-- Add your settings options here -->
<p>Settings page content will go here.</p>
</div>
</div>
"""tabs.js
// Function to generate a unique ID
function generateUUID() {
return crypto.randomUUID();
}
// Event listener for the DOM loaded
document.addEventListener('DOMContentLoaded', async () => {
const homeLink = document.getElementById('homeLink');
const searchInput = document.getElementById('searchInput');
const settingsButton = document.getElementById('settingsButton');
const tabsContent = document.getElementById('tabsContent');
const settingsContent = document.getElementById('settingsContent');
let savedTabGroups = [];
let tabsToMove = [];
let groupIdOfMovingTabs = '';
// Load saved tab groups when the page loads and display it
await getSavedTabGroupsFromStorage();
displayTabGroups();
// Event listener for messages from background.js
chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
if (message.action === 'tabs_saved') {
// Reload saved tab groups and repaint the DOM
await getSavedTabGroupsFromStorage();
displayTabGroups();
}
});
// Event listener for the 'Home' link (extension name)
homeLink.addEventListener('click', (event) => {
event.preventDefault(); // Prevent default link behavior
// Show the search input
searchInput.style.display = 'block';
// Show tabs content and hide settings content
tabsContent.style.display = 'block';
settingsContent.style.display = 'none';
});
// Event listener for the search bar
searchInput.addEventListener('input', () => {
// TODO: disable or enable (by settings) to move tabs when filtering
// if(!settings.canMoveWhileFiltering) {
// tabsToMove = [];
// groupIdOfMovingTabs = '';
// }
// Repaint the DOM
displayTabGroups();
});
// Event listener for the 'Settings' button
settingsButton.addEventListener('click', (event) => {
event.preventDefault(); // Prevent default link behavior
// Hide the search input
searchInput.style.display = 'none';
// Hide tabs content and show settings content
tabsContent.style.display = 'none';
settingsContent.style.display = 'block';
});
// Function to get saved tabs from storage
async function getSavedTabGroupsFromStorage() {
const data = await chrome.storage.local.get('savedTabGroups');
savedTabGroups = data.savedTabGroups || [];
}
// Function to set saved tabs to storage
async function setSavedTabGroupsToStorage() {
await chrome.storage.local.set({ 'savedTabGroups': savedTabGroups }, () => {
// Check for errors
if (chrome.runtime.lastError) {
console.error('Error setting storage:', chrome.runtime.lastError);
// TODO: Handle the error accordingly
}
});
}
// Function to display tab groups on the page
function displayTabGroups() {
const fragment = document.createDocumentFragment(); // Create fragment to minimizes the number of reflows and repaints
const currentSearchQuery = searchInput.value.trim().toLowerCase(); // Get current filtering query
const areThereAnyTabsToMove = (tabsToMove.length !== 0) && (savedTabGroups.findIndex(g => g.id === groupIdOfMovingTabs) !== -1);
savedTabGroups.forEach((group) => {
let anyTabVisible = false;
const groupId = group.id;
// Create a container for each group
const groupContainer = document.createElement('div');
groupContainer.className = 'tabGroup';
groupContainer.dataset.groupId = groupId;
// Create a header container for the group
const groupHeaderContainer = document.createElement('div');
groupHeaderContainer.className = 'groupHeaderContainer';
// Add an event listener to toggle collapse/expand
groupHeaderContainer.addEventListener('click', (event) => {
// Check if the clicked element is the header container or the group title
if ((event.target === groupHeaderContainer) || ((event.target === groupTitle) && (editGroupButton.dataset.mode === 'edit'))) {
toggleGroupCollapse(groupId);
}
});
// Create the master checkbox
const masterCheckbox = document.createElement('input');
masterCheckbox.type = 'checkbox';
masterCheckbox.className = 'masterCheckbox';
masterCheckbox.title = 'Select/Deselect All Tabs in this Group';
// Add an event listener to the master checkbox
masterCheckbox.addEventListener('change', (event) => {
toggleGroupCheckboxes(groupId, event.target.checked);
});
// Create a title for the group
const groupTitle = document.createElement('h2');
groupTitle.textContent = group.category;
groupTitle.className = 'groupTitle';
groupTitle.contentEditable = false;
// Create an edit button for the group title
const editGroupButton = document.createElement('button');
editGroupButton.textContent = 'Edit title';
editGroupButton.title = 'Edit group title';
editGroupButton.className = 'editGroupButton';
editGroupButton.dataset.mode = 'edit';
editGroupButton.addEventListener('click', () => {
toggleEditGroupTitle(groupId);
});
// Create a restore button for the group
const restoreGroupButton = document.createElement('button');
restoreGroupButton.textContent = 'Restore';
restoreGroupButton.title = 'Restore this group';
restoreGroupButton.className = 'restoreGroupButton';
restoreGroupButton.addEventListener('click', () => {
restoreTabGroup(groupId);
});
// Create a remove button for the group
const removeGroupButton = document.createElement('button');
removeGroupButton.textContent = 'Remove';
removeGroupButton.title = 'Remove this group';
removeGroupButton.className = 'removeGroupButton';
removeGroupButton.addEventListener('click', () => {
removeTabGroup(groupId);
});
// Append elements to the header container in the desired order
groupHeaderContainer.appendChild(masterCheckbox);
groupHeaderContainer.appendChild(groupTitle);
groupHeaderContainer.appendChild(editGroupButton);
groupHeaderContainer.appendChild(restoreGroupButton);
groupHeaderContainer.appendChild(removeGroupButton);
// Create a list for the tabs in the group
const tabList = document.createElement('ul');
tabList.className = 'tabList';
tabList.style.display = group.collapsed ? 'none' : 'block';
group.tabs.forEach((tab) => {
const tabId = tab.id;
// Create a list item for each tab
const listItem = document.createElement('li');
listItem.dataset.tabId = tabId;
// Create "Move here" button
const moveHereButton = document.createElement('button');
moveHereButton.textContent = 'Move here'; // Using a star symbol for simplicity
moveHereButton.className = 'moveHereButton';
moveHereButton.style.display = areThereAnyTabsToMove && (groupIdOfMovingTabs != groupId) ? 'block' : 'none';
moveHereButton.addEventListener('click', () => {
moveTabsHere(groupId, tabId);
});
// Create a container for the tab info and controls
const tabContainer = document.createElement('div');
tabContainer.className = 'tabContainer';
// Create a checkbox for selection
const checkbox = document.createElement('input');
checkbox.type = 'checkbox';
checkbox.className = 'tabCheckbox';
checkbox.addEventListener('change', () => {
updateMasterCheckboxState(groupId);
});
// Create a link to store tab informations
const link = document.createElement('a');
link.href = tab.url;
link.textContent = tab.title;
link.target = '_blank';
// Create a remove button for the tab
const removeTabButton = document.createElement('button');
removeTabButton.textContent = 'X';
removeTabButton.title = 'Remove this tab';
removeTabButton.className = 'removeTabButton';
removeTabButton.addEventListener('click', () => {
removeTabFromGroup(groupId, tabId);
});
// Append elements to the tab container in the desired order
tabContainer.appendChild(checkbox);
tabContainer.appendChild(link);
tabContainer.appendChild(removeTabButton);
// Append elements to the list item in the desired order
listItem.appendChild(moveHereButton);
listItem.appendChild(tabContainer);
// Append element to the tab list
tabList.appendChild(listItem);
// Show or hide the tab based on whether the query is included in the title
if (tab.title.toLowerCase().includes(currentSearchQuery)) {
listItem.style.display = 'flex';
anyTabVisible = true;
} else {
listItem.style.display = 'none';
}
});
// Create "Move here" button
const moveHereButton = document.createElement('button');
moveHereButton.textContent = 'Move here'; // Using a star symbol for simplicity
moveHereButton.className = 'moveHereButton';
moveHereButton.style.display = areThereAnyTabsToMove && (groupIdOfMovingTabs != groupId) ? 'block' : 'none';
moveHereButton.addEventListener('click', () => {
moveTabsHere(groupId, '');
});
// Create a footer container for the group
const groupFooterContainer = document.createElement('div');
groupFooterContainer.className = 'groupFooterContainer';
groupFooterContainer.style.display = group.collapsed ? 'none' : 'flex';
// Add a button to move selected tabs
const moveSelectedButton = document.createElement('button');
moveSelectedButton.textContent = 'Move Selected Tabs';
moveSelectedButton.className = 'moveSelectedButton'; // Add class for styling
moveSelectedButton.disabled = areThereAnyTabsToMove && (groupIdOfMovingTabs != groupId);
moveSelectedButton.style.textDecoration = moveSelectedButton.disabled ? 'line-through' : 'none';
moveSelectedButton.addEventListener('click', () => {
moveSelectedTabs(groupId);
});
// Add a button to restore selected tabs
const restoreSelectedButton = document.createElement('button');
restoreSelectedButton.textContent = 'Restore Selected Tabs';
restoreSelectedButton.className = 'restoreSelectedButton';
restoreSelectedButton.addEventListener('click', () => {
restoreSelectedTabs(groupId);
});
// Add a button to remove selected tabs
const removeSelectedButton = document.createElement('button');
removeSelectedButton.textContent = 'Remove Selected Tabs';
removeSelectedButton.className = 'removeSelectedButton';
removeSelectedButton.addEventListener('click', () => {
removeSelectedTabs(groupId);
});
// Create a span to display the number of tabs
const tabsCountSpan = document.createElement('h2');
tabsCountSpan.textContent = `${group.tabs.length} Page${group.tabs.length !== 1 ? 's' : ''}`;
tabsCountSpan.className = 'tabsCount';
// Append the removeSelectedButton to the footer container
groupFooterContainer.appendChild(moveSelectedButton);
groupFooterContainer.appendChild(restoreSelectedButton);
groupFooterContainer.appendChild(removeSelectedButton);
groupFooterContainer.appendChild(tabsCountSpan);
// Append elements to the group container
groupContainer.appendChild(groupHeaderContainer);
groupContainer.appendChild(tabList);
groupContainer.appendChild(moveHereButton);
groupContainer.appendChild(groupFooterContainer);
// Show or hide the group based on whether any tabs are visible
if (anyTabVisible) {
groupContainer.style.display = 'block';
} else {
groupContainer.style.display = 'none';
}
// Append the group container to the main container
fragment.appendChild(groupContainer);
});
// Clear existing content and append the fragment
const tabGroupsContainer = document.getElementById('tabGroups');
tabGroupsContainer.innerHTML = '';
tabGroupsContainer.appendChild(fragment);
// Display a message if no tabs match
displayResultMessage();
}
// Function to toggle group collapse/expand state
function toggleGroupCollapse(groupId) {
// Find the group index
const groupIndex = savedTabGroups.findIndex(g => g.id === groupId);
if (groupIndex === -1) return;
// Get HTML elements
const groupContainer = document.querySelector(`.tabGroup[data-group-id="${groupId}"]`);
const tabList = groupContainer.querySelector('.tabList');
const groupFooterContainer = groupContainer.querySelector('.groupFooterContainer');
// Toggle the display style
if (savedTabGroups[groupIndex].collapsed) {
tabList.style.display = 'block';
groupFooterContainer.style.display = 'flex';
} else {
tabList.style.display = 'none';
groupFooterContainer.style.display = 'none';
}
savedTabGroups[groupIndex].collapsed ^= true; // toggle value
// Save the updated savedTabGroups
setSavedTabGroupsToStorage();
}
// Function to toggle all checkboxes in a group
function toggleGroupCheckboxes(groupId, isChecked) {
const groupContainer = document.querySelector(`.tabGroup[data-group-id="${groupId}"]`);
const checkboxes = groupContainer.querySelectorAll('.tabCheckbox');
checkboxes.forEach((checkbox) => {
checkbox.checked = isChecked;
});
}
// Function to update the master checkbox state based on individual checkboxes
function updateMasterCheckboxState(groupId) {
const groupContainer = document.querySelector(`.tabGroup[data-group-id="${groupId}"]`);
const masterCheckbox = groupContainer.querySelector('.masterCheckbox');
const checkboxes = groupContainer.querySelectorAll('.tabCheckbox');
const allChecked = Array.from(checkboxes).every(checkbox => checkbox.checked);
const anyChecked = Array.from(checkboxes).some(checkbox => checkbox.checked);
masterCheckbox.checked = allChecked;
masterCheckbox.indeterminate = !allChecked && anyChecked;
}
// Function to toggle between edit and save modes for the group title
function toggleEditGroupTitle(groupId) {
// Find the group index
const groupIndex = savedTabGroups.findIndex(g => g.id === groupId);
if (groupIndex === -1) return;
// Get HTML elements
const groupHeaderContainer = document.querySelector(`.tabGroup[data-group-id="${groupId}"] .groupHeaderContainer`);
const groupTitle = groupHeaderContainer.querySelector('.groupTitle');
const editGroupButton = groupHeaderContainer.querySelector('.editGroupButton');
if (editGroupButton.dataset.mode === 'edit') {
// Switch to edit mode
groupTitle.contentEditable = true;
groupTitle.focus();
// Move cursor to the end of the text using Range and Selection APIs
if ((typeof window.getSelection != "undefined") && (typeof document.createRange != "undefined")) {
const range = document.createRange();
range.selectNodeContents(groupTitle);
range.collapse(false); // Collapse the range to the end
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
}
// Change button to 'Save'
editGroupButton.textContent = 'Save';
editGroupButton.title = 'Save group title';
editGroupButton.dataset.mode = 'save';
// Handle Enter key to save
groupTitle.onkeypress = function(e) {
if (e.key === 'Enter') {
e.preventDefault(); // Prevent newline
toggleEditGroupTitle(groupId); // Save on Enter key
}
};
} else {
// Switch to view mode (save changes)
const newTitle = groupTitle.textContent.trim();
if (newTitle === '') {
alert('Group title cannot be empty.');
groupTitle.focus();
return;
}
// Check if a group with the new title already exists
if (savedTabGroups.some(g => (g.category === newTitle) && (g.id !== groupId))) {
alert('A group with this title already exists. Please choose a different title.');
groupTitle.focus();
return;
}
// Update the group title
savedTabGroups[groupIndex].category = newTitle;
// Save the updated tab groups to storage
setSavedTabGroupsToStorage();
// Disable contentEditable
groupTitle.contentEditable = false;
// Reset the edit button
editGroupButton.textContent = 'Edit';
editGroupButton.title = 'Edit group title';
editGroupButton.dataset.mode = 'edit';
// Remove keypress handler
groupTitle.onkeypress = null;
}
}
// Function to move selected tabs
function moveSelectedTabs(groupId) {
// Enable to move tabs
if (tabsToMove.length === 0) {
// Find the group by ID
const group = savedTabGroups.find(g => g.id === groupId);
if (!group) return;
// Get HTML elements
const groupContainer = document.querySelector(`.tabGroup[data-group-id="${groupId}"]`);
const checkboxes = groupContainer.querySelectorAll('.tabCheckbox');
// Collect the tabs to move
tabsToMove = [];
checkboxes.forEach((checkbox, checkboxIndex) => {
if (checkbox.checked) {
tabsToMove.push(group.tabs[checkboxIndex]);
}
});
if (tabsToMove.length === 0) {
alert('Please select at least one tab to move.');
return;
}
// Saves the group ID of the group where the tabs to be moved were taken
groupIdOfMovingTabs = groupId;
// Disable all the others moving buttons
document.querySelectorAll('.moveSelectedButton').forEach(moveSelectedButton => {
if (moveSelectedButton.parentElement.parentElement.dataset.groupId != groupId) {
moveSelectedButton.disabled = true;
moveSelectedButton.style.textDecoration = 'line-through';
}
});
// Remove bottom border from all the tabs
document.querySelectorAll('.tabList li').forEach(listItem => {
listItem.style.borderBottomWidth = '0px';
});
// Show all "Move here" buttons
document.querySelectorAll('.moveHereButton').forEach(moveHereButton => {
moveHereButton.style.display = 'block';
});
}
// Disable to move tabs
else {
// Clear the array and the group ID
tabsToMove = [];
groupIdOfMovingTabs = '';
// Enable all the others buttons
document.querySelectorAll('.moveSelectedButton').forEach(moveSelectedButton => {
if (moveSelectedButton.parentElement.parentElement.dataset.groupId != groupId) {
moveSelectedButton.disabled = false;
moveSelectedButton.style.textDecoration = 'none';
}
});
// Add bottom border in all the tabs
document.querySelectorAll('.tabList li').forEach(listItem => {
listItem.style.borderBottomWidth = '1px';
});
// Hide all "Move here" buttons
document.querySelectorAll('.moveHereButton').forEach(moveHereButton => {
moveHereButton.style.display = 'none';
});
}
}
// Function to restore selected tabs from a group
function restoreSelectedTabs(groupId) {
// Find the group by ID
const group = savedTabGroups.find(g => g.id === groupId);
if (!group) return;
// Get HTML elements
const groupContainer = document.querySelector(`.tabGroup[data-group-id="${groupId}"]`);
const checkboxes = groupContainer.querySelectorAll('.tabCheckbox');
// Collect the tabs to restore
const tabsToRestore = [];
checkboxes.forEach((checkbox, checkboxIndex) => {
if (checkbox.checked) {
tabsToRestore.push(group.tabs[checkboxIndex]);
}
});
if (tabsToRestore.length === 0) {
alert('Please select at least one tab to restore.');
return;
}
// Confirm restoration
if (!confirm(`Are you sure you want to restore ${tabsToRestore.length} selected tab(s)?`)) {
return;
}
// Restore the selected tabs by creating new tabs in the browser
tabsToRestore.forEach(tab => {
chrome.tabs.create({ url: tab.url });
});
}
// Function to remove selected tabs from a group
function removeSelectedTabs(groupId) {
// Find the group index
const groupIndex = savedTabGroups.findIndex(g => g.id === groupId);
if (groupIndex === -1) return;
// Get HTML elements
const groupContainer = document.querySelector(`.tabGroup[data-group-id="${groupId}"]`);
const tabList = groupContainer.querySelector('.tabList');
const checkboxes = groupContainer.querySelectorAll('.tabCheckbox');
// Collect the indices of tabs to remove
const indicesToRemove = [];
checkboxes.forEach((checkbox, checkboxIndex) => {
if (checkbox.checked) {
indicesToRemove.push(checkboxIndex);
}
});
if (indicesToRemove.length === 0) {
alert('Please select at least one tab to remove.');
return;
}
// Confirm to remove the tabs
if (!confirm('Are you sure you want to remove the selected tabs?')) {
return;
}
// Remove tabs starting from the highest index to avoid index shifting
indicesToRemove.sort((a, b) => b - a).forEach((tabIndex) => {
tabList.removeChild(tabList.children[tabIndex]);
savedTabGroups[groupIndex].tabs.splice(tabIndex, 1);
});
// Remove the group if no tabs are left
if (savedTabGroups[groupIndex].tabs.length === 0) {
removeTabGroup(groupId);
return;
}
// Update tabs count
updateTabCount(groupId);
// Save the updated savedTabGroups
setSavedTabGroupsToStorage();
}
// Function to update tabs count
function updateTabCount(groupId) {
// Get group
const group = savedTabGroups.find(g => g.id === groupId);
if (!group) return;
// Get HTML elements
const groupContainer = document.querySelector(`.tabGroup[data-group-id="${groupId}"]`);
if (!groupContainer) return;
const tabsCountSpan = groupContainer.querySelector('.tabsCount');
if (!tabsCountSpan) return;
// Change text
tabsCountSpan.textContent = `${group.tabs.length} Page${group.tabs.length !== 1 ? 's' : ''}`;
}
// Function to remove an entire tab group
function removeTabGroup(groupId) {
// Find the group index
const groupIndex = savedTabGroups.findIndex(g => g.id === groupId);
if (groupIndex === -1) return;
// Get HTML element
const groupContainer = document.querySelector(`.tabGroup[data-group-id="${groupId}"]`);
// Remove the group
groupContainer.parentElement.removeChild(groupContainer);
savedTabGroups.splice(groupIndex, 1);
// Display a message if there are no tabs
displayResultMessage();
// Save the updated savedTabGroups
setSavedTabGroupsToStorage();
}
// Function to remove a tab from a group
function removeTabFromGroup(groupId, tabId) {
// Find the group index
const groupIndex = savedTabGroups.findIndex(g => g.id === groupId);
if (groupIndex === -1) return;
// Find the tab index
const tabIndex = savedTabGroups[groupIndex].tabs.findIndex(t => t.id === tabId);
if (tabIndex === -1) return;
// Get HTML element
const tabList = document.querySelector(`.tabGroup[data-group-id="${groupId}"] .tabList`);
// Remove tab
tabList.removeChild(tabList.children[tabIndex]);
savedTabGroups[groupIndex].tabs.splice(tabIndex, 1);
// Remove the group if no tabs are left
if (savedTabGroups[groupIndex].tabs.length === 0) {
removeTabGroup(groupId);
return;
}
// Update tabs count
updateTabCount(groupId);
// Save the updated savedTabGroups
setSavedTabGroupsToStorage();
}
// Function to move tabs inside a group
function moveTabsHere(groupId, tabId) {
if ((tabsToMove.length === 0) || (savedTabGroups.findIndex(g => g.id === groupIdOfMovingTabs) === -1)) return;
// Find the group index
let groupIndex = savedTabGroups.findIndex(g => g.id === groupId);
if (groupIndex === -1) return;
// Find the tab index
let tabIndex = savedTabGroups[groupIndex].tabs.findIndex(t => t.id === tabId);
if (tabIndex < 0) tabIndex = savedTabGroups[groupIndex].tabs.length;
// Check if the tabs we are moving have the same ID as those in the group
let groupIds = new Set();
let tabToAdd = JSON.parse(JSON.stringify(tabsToMove)); // Make a deep copy
do {
// Get group tabs IDs
groupIds = new Set(savedTabGroups[groupIndex].tabs.map(tab => tab.id));
// Check for duplicated IDs
tabToAdd.forEach(tab => {
if (groupIds.has(tab.id)) {
tab.id = generateUUID(); // generate new ID
}
});
} while(tabToAdd.some(tab => groupIds.has(tab.id)));
// Add tabs
savedTabGroups[groupIndex].tabs.splice(tabIndex, 0, ...tabToAdd);
// Remove tabs from previous group
groupIndex = savedTabGroups.findIndex(g => g.id === groupIdOfMovingTabs);
groupIds = new Set(tabsToMove.map(tab => tab.id));
savedTabGroups[groupIndex].tabs = savedTabGroups[groupIndex].tabs.filter(tab => !groupIds.has(tab.id));
// Clear the array and the group ID
tabsToMove = [];
groupIdOfMovingTabs = '';
// Save the updated savedTabGroups
setSavedTabGroupsToStorage();
// Repaint the DOM (TODO: remove this and make it repaint dynamically when adding and removing moved tabs)
displayTabGroups();
}
// Function to restore tabs from a single group
function restoreTabGroup(groupId) {
// Find the group by ID
const group = savedTabGroups.find(g => g.id === groupId);
if (!group) return;
// Restore tabs
group.tabs.forEach(tab => {
chrome.tabs.create({ url: tab.url });
});
}
// Display a message if there are no tabs visible in the page
function displayResultMessage() {
// Get HTML elements
const resultMessage = document.querySelector('#resultMessage');
const groupContainer = document.querySelectorAll('.tabGroup');
// Check if any group is visible
let anyGroupsVisible = Object.values(groupContainer).some(group => group.style.display === 'block');
// Display message
if (savedTabGroups.length === 0) {
resultMessage.style.display = 'block';
resultMessage.textContent = 'No tabs saved. Try adding some.';
}
else if (!anyGroupsVisible) {
resultMessage.style.display = 'block';
resultMessage.textContent = 'No tabs match your search.';
}
else {
resultMessage.style.display = 'none';
resultMessage.textContent = '';
}
}
You've developed a Chrome extension aimed at managing and organizing open tabs, similar to popular extensions like OneTab and Better OneTab. Below is a breakdown of the components you've provided, along with suggestions and potential improvements to enhance functionality and user experience.
1. manifest.json
Purpose: Defines the extension's configuration, permissions, and resources.
Key Components:
manifest_version: Specifies the version of the manifest file format. Version 3 is the latest and recommended.
name, version, description: Basic metadata about the extension.
permissions: Grants the extension access to tabs, storage, and context menus.
background: Specifies background.js as the service worker.
action: Defines the default icons for the extension's toolbar button.
Suggestions:
Icons: Ensure that all icon sizes (16, 32, 48, 128) are provided and optimized for clarity.
Additional Permissions: Depending on future features, you might need to request additional permissions. Always adhere to the principle of least privilege to maintain user trust.
2. background.js
Purpose: Handles background tasks such as context menu creation, managing tab saving logic, and responding to user interactions via the extension icon or context menus.
Key Features:
Unique ID Generation: Uses crypto.randomUUID() to assign unique identifiers to saved tab groups and individual tabs.
Context Menu Options: Provides various options like saving tabs to the left/right of the current tab, saving all tabs, excluding the current tab, or saving only the current tab.
Tab Saving Logic: Filters tabs based on criteria (e.g., excluding pinned tabs, ensuring URLs start with http), saves them into chrome.storage.local, and closes the saved tabs.
Messaging: Communicates with tabs.html to refresh the UI when tabs are saved.
Suggestions:
Error Handling:
Storage Operations: While you've added a console log for storage operations, consider providing user feedback (e.g., notifications) in case of failures.
Tab Operations: Handle scenarios where tabs cannot be removed (e.g., if a tab has been already closed).
Unique Category Names:
Current Implementation: You've commented out the while loop that ensures unique category names.
Recommendation: Reinstate and refine this logic to prevent duplicate category names, enhancing user clarity.
Performance Optimization:
Tab Removal: Bulk removing tabs (chrome.tabs.remove) could be optimized by batching operations or providing progress feedback for large numbers of tabs.
Context Menu Contexts:
Current Context: You've set context menus to appear in the action (toolbar) context.
Enhancement: Consider adding context menu options in other relevant contexts, such as right-clicking on the page or individual tabs.
3. tabs.html
Purpose: Serves as the main UI for the extension, allowing users to view, manage, and manipulate saved tab groups.
Key Components:
Header: Contains the extension name (Tab Manager), a search input, and a settings button.
Main Content: Displays saved tab groups and a settings section.
Scripts and Styles: Links to tabs.js for functionality and tabs.css for styling.
Suggestions:
Accessibility:
ARIA Labels: Enhance accessibility by adding ARIA labels to interactive elements (e.g., buttons, checkboxes).
Keyboard Navigation: Ensure that all functionalities are accessible via keyboard for users who rely on it.
Responsive Design:
Mobile Devices: Although Chrome extensions are primarily used on desktops, ensuring responsiveness can improve usability on varied screen sizes.
User Feedback:
Loading Indicators: While Loading saved data... is displayed, consider adding spinners or progress bars for better user experience during data fetches.
4. tabs.js
Purpose: Provides interactivity and logic for the tabs.html UI, including displaying saved tab groups, handling user actions (restore, edit, remove), and managing data storage.
Key Features:
DOM Manipulation: Dynamically creates and updates UI elements based on saved tab groups.
Event Handling: Listens for user interactions like clicking buttons, editing titles, moving tabs, etc.
Storage Management: Retrieves and updates stored tab groups in chrome.storage.local.
Suggestions:
Code Organization:
Modularity: Consider breaking down the script into smaller modules or using classes to handle different responsibilities (e.g., TabGroupManager, UIHandler).
Comments and Documentation: Enhance inline comments to explain complex logic, which aids future maintenance and collaboration.
Performance Enhancements:
Debouncing Search Input: Implement debouncing on the search input to prevent excessive UI re-rendering during rapid typing.
Efficient Rendering: Utilize techniques like virtual scrolling if the number of tab groups or tabs becomes large, ensuring smooth performance.
Error Handling:
API Calls: Handle potential errors from Chrome APIs (e.g., chrome.tabs.create) gracefully, providing user feedback if operations fail.
Data Integrity: Ensure that operations modifying savedTabGroups maintain data integrity, especially in concurrent scenarios.
Security Considerations:
Input Sanitization: When editing group titles or handling user input, sanitize inputs to prevent potential security vulnerabilities like script injection.
Feature Enhancements:
Drag and Drop: Implement drag-and-drop functionality for reordering tabs within groups or moving them between groups.
Batch Operations: Allow batch renaming, moving, or removing of multiple groups or tabs for efficiency.
Export/Import Functionality: Enable users to export their tab configurations and import them on other devices or after reinstallation.
5. tabs.css
Purpose: Styles the tabs.html UI, ensuring a clean and user-friendly interface.
Key Features:
Flexbox Layouts: Utilizes Flexbox for arranging header elements, group containers, and buttons.
Responsive Elements: Ensures that buttons, inputs, and other interactive elements are visually consistent and accessible.
Theming: Applies color schemes and hover effects to enhance interactivity and visual appeal.
Suggestions:
Consistency:
Button Styles: Maintain consistent padding, margins, and font sizes across all button types for a uniform look.
Color Scheme: Ensure that color contrasts meet accessibility standards (e.g., WCAG) to accommodate users with visual impairments.
Responsive Design Enhancements:
Media Queries: Implement media queries to adjust layouts for different screen sizes, ensuring usability across devices.
Flexible Units: Use relative units (e.g., em, rem, %) instead of fixed units (px) where appropriate for better scalability.
Animations and Transitions:
Interactive Feedback: Add subtle animations or transitions to button clicks, group collapses/expansions, and hover states to enrich user experience.
Performance: Ensure that animations are smooth and do not hinder performance, especially on lower-end devices.
Code Maintainability:
CSS Variables: Utilize CSS variables for commonly used values (e.g., colors, spacing) to simplify updates and theming.
BEM Methodology: Consider adopting BEM (Block, Element, Modifier) naming conventions for classes to enhance readability and maintainability.
General Recommendations
Testing:
Automated Tests: Implement unit and integration tests to ensure that functionalities work as expected and to prevent regressions during future development.
User Testing: Conduct user testing sessions to gather feedback on usability, performance, and feature set.
Performance Monitoring:
Profiling: Use Chrome's Developer Tools to profile and identify any performance bottlenecks, especially when handling large numbers of tabs.
Optimization: Optimize resource usage, ensuring that the extension remains lightweight and doesn't adversely affect browser performance.
Documentation:
User Guide: Create a comprehensive user guide or help section within the extension to assist users in leveraging all features effectively.
Developer Documentation: Maintain clear developer documentation for future reference and to aid any collaborators.
Security Best Practices:
Content Security Policy (CSP): Ensure strict adherence to CSP to prevent cross-site scripting (XSS) and other vulnerabilities.
Data Privacy: Clearly communicate how user data (saved tabs) is handled, stored, and protected, building trust with users.
Future Enhancements:
Synchronization: Allow users to sync their saved tab groups across devices using Chrome's identity API.
Search and Filtering: Enhance search capabilities with advanced filtering options (e.g., by date saved, frequency of use).
Customization: Provide users with customization options for group colors, icons, and other UI elements to personalize their experience.
Next Steps
To assist you further, please consider specifying:
Desired Features or Changes: Any particular functionality you wish to add or modify.
Issues Encountered: If you're facing specific bugs or performance issues.
Design Preferences: Any changes in the UI/UX that you're aiming for.
Performance Goals: Targets you have for optimization or resource usage.
With more detailed information, I can provide targeted guidance, code snippets, or architectural recommendations to help you achieve your development goals.