-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
79 lines (71 loc) · 2.5 KB
/
background.js
File metadata and controls
79 lines (71 loc) · 2.5 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
72
73
74
75
76
77
78
79
/**
* Background Service Worker for Wikipedia Birthplace Corrector Extension
* Handles state management, message routing, and badge updates
*/
// Cross-browser compatibility: Firefox uses browser.browserAction, Chrome uses chrome.action
const browserAPI = typeof browser !== 'undefined' ? browser : chrome;
const badgeAPI = browserAPI.action || browserAPI.browserAction;
// Initialize extension state on install
chrome.runtime.onInstalled.addListener(() => {
chrome.storage.sync.get('enabled', (result) => {
if (result.enabled === undefined) {
chrome.storage.sync.set({ enabled: true });
}
});
chrome.storage.local.get('replacementCount', (result) => {
if (result.replacementCount === undefined) {
chrome.storage.local.set({ replacementCount: 0 });
}
});
});
// Handle messages from content scripts
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.type === 'incrementCount') {
chrome.storage.local.get('replacementCount', (result) => {
const newCount = (result.replacementCount || 0) + (request.count || 1);
chrome.storage.local.set({ replacementCount: newCount });
updateBadge(newCount);
});
} else if (request.type === 'getState') {
chrome.storage.sync.get('enabled', (result) => {
sendResponse({ enabled: result.enabled !== false });
});
return true; // Keep channel open for async response
}
});
/**
* Format a number for badge display
* @param {number} count - The count to format
* @returns {string} Formatted count (e.g., "1.2k" for 1234)
*/
function formatBadgeText(count) {
if (count === 0) {
return '';
}
if (count < 1000) {
return count.toString();
}
if (count < 1000000) {
const thousands = Math.floor(count / 100) / 10;
return thousands.toFixed(thousands % 1 === 0 ? 0 : 1) + 'k';
}
const millions = Math.floor(count / 100000) / 10;
return millions.toFixed(millions % 1 === 0 ? 0 : 1) + 'm';
}
/**
* Update the extension badge with replacement count
* @param {number} count - The replacement count to display
*/
function updateBadge(count) {
const badgeText = formatBadgeText(count);
if (badgeAPI && badgeAPI.setBadgeText) {
badgeAPI.setBadgeText({ text: badgeText });
badgeAPI.setBadgeBackgroundColor({ color: '#4CAF50' });
}
}
// Listen for storage changes to update badge
chrome.storage.onChanged.addListener((changes, areaName) => {
if (areaName === 'local' && changes.replacementCount) {
updateBadge(changes.replacementCount.newValue || 0);
}
});