forked from RagnarokFate/TabRenamer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
71 lines (63 loc) · 2.17 KB
/
background.js
File metadata and controls
71 lines (63 loc) · 2.17 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
// Store current custom names for tabs
const customTabNames = new Map();
// Initialize when extension is installed or updated
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.local.get(['recentNames', 'savedUrls'], (data) => {
if (!data.recentNames) {
chrome.storage.local.set({ recentNames: [] });
}
if (!data.savedUrls) {
chrome.storage.local.set({ savedUrls: {} });
}
});
});
// Listen for tab URL changes to apply saved names
chrome.tabs.onUpdated.addListener((tabId, changeInfo, tab) => {
if (changeInfo.status === 'complete' && tab.url) {
applySavedNameIfExists(tabId, tab.url);
}
});
// Check if a URL has a saved name
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'checkSavedUrl' && sender.tab) {
applySavedNameIfExists(sender.tab.id, message.url);
} else if (message.action === 'getTabName' && sender.tab) {
// Return the custom name for the tab if it exists
const customName = customTabNames.get(sender.tab.id);
sendResponse({ name: customName });
}
return true;
});
// When a tab is renamed, store the custom name
chrome.runtime.onMessage.addListener((message, sender, sendResponse) => {
if (message.action === 'setTabName' && message.tabId && message.name) {
customTabNames.set(message.tabId, message.name);
sendResponse({ success: true });
}
return true;
});
// Clean up when tabs are closed
chrome.tabs.onRemoved.addListener((tabId) => {
customTabNames.delete(tabId);
});
// Apply saved name if it exists for this URL
async function applySavedNameIfExists(tabId, url) {
try {
const hostname = new URL(url).hostname;
const data = await chrome.storage.local.get(['savedUrls']);
const savedUrls = data.savedUrls || {};
if (savedUrls[hostname]) {
// Store the custom name
customTabNames.set(tabId, savedUrls[hostname]);
// Wait a moment for the page to fully load
setTimeout(() => {
chrome.tabs.sendMessage(tabId, {
action: 'renameTab',
name: savedUrls[hostname]
});
}, 500);
}
} catch (error) {
console.error('Error applying saved name:', error);
}
}