-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
34 lines (29 loc) · 1.03 KB
/
background.js
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
chrome.runtime.onInstalled.addListener(() => {
console.log("Extension installed");
chrome.storage.local.set({ urlMapping: {}, counter: 1 });
});
chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
if (request.action === "shortenURL") {
chrome.storage.local.get(["urlMapping", "counter"], ({ urlMapping = {}, counter = 1 }) => {
const shortUrlKey = generateShortUrlKey(counter);
const shortUrl = `${chrome.runtime.getURL('')}?key=${shortUrlKey}`;
urlMapping[shortUrlKey] = request.url;
chrome.storage.local.set({ urlMapping, counter: counter + 1 }, () => {
sendResponse({ shortUrl });
});
});
return true; // Indicate async response
}
});
function generateShortUrlKey(counter) {
return toBase62(counter);
}
function toBase62(num) {
const chars = '0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ';
let result = '';
do {
result = chars[num % 62] + result;
num = Math.floor(num / 62);
} while (num > 0);
return result;
}