forked from clawfire/chrome-webhook-extension
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbackground.js
More file actions
794 lines (729 loc) · 25.5 KB
/
background.js
File metadata and controls
794 lines (729 loc) · 25.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
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
// Webhook queue management
const webhookQueues = new Map(); // Map of webhookUrl -> { queue: [], lastSent: timestamp, timer: timeoutId }
const queueNotifications = new Map(); // Map of notificationId -> { webhookUrl, intervalId }
chrome.runtime.onInstalled.addListener(() => {
chrome.contextMenus.create(
{
id: "sendToWebhook",
title: "Send to Webhook",
contexts: ["page", "link", "image", "selection", "video"],
},
() => {
if (chrome.runtime.lastError) {
console.error(
`Error creating parent menu: ${chrome.runtime.lastError.message}`,
);
}
updateWebhookMenus();
},
);
initializeQueues();
});
chrome.runtime.onStartup.addListener(() => {
updateWebhookMenus();
initializeQueues();
});
/**
* Initializes webhook queues from local storage.
* It retrieves stored webhooks and sets up their initial queue data
* including an empty queue, last sent timestamp, timer, and rate limit.
*/
function initializeQueues() {
chrome.storage.local.get("webhooks", (data) => {
if (data.webhooks) {
data.webhooks.forEach((webhook) => {
if (!webhookQueues.has(webhook.url)) {
webhookQueues.set(webhook.url, {
queue: [],
lastSent: 0,
timer: null,
rateLimit: webhook.rateLimit || 0,
});
} else {
// Update rate limit if it changed
const queueData = webhookQueues.get(webhook.url);
queueData.rateLimit = webhook.rateLimit || 0;
}
});
}
});
}
/**
* Adds a payload to a specific webhook's queue.
* If the webhook's queue doesn't exist, it initializes it.
* It also checks if the item will be queued due to rate limiting and
* displays a notification if so, then attempts to process the queue.
*
* @param {string} webhookUrl - The URL of the webhook.
* @param {object} payload - The data payload to send to the webhook.
* @param {string} webhookName - The name of the webhook for display purposes.
* @param {number} [rateLimit=0] - The rate limit in seconds for this webhook (0 for no limit).
*/
function addToQueue(webhookUrl, payload, webhookName, rateLimit = 0) {
if (!webhookQueues.has(webhookUrl)) {
webhookQueues.set(webhookUrl, {
queue: [],
lastSent: 0,
timer: null,
rateLimit,
});
}
const queueData = webhookQueues.get(webhookUrl);
queueData.rateLimit = rateLimit; // Update rate limit
queueData.queue.push({ payload, webhookName, timestamp: Date.now() });
// Check if this item will be queued (not sent immediately)
const now = Date.now();
const timeSinceLastSent = now - queueData.lastSent;
const rateLimitMs = queueData.rateLimit * 1000;
const willBeQueued =
queueData.rateLimit > 0 &&
(queueData.queue.length > 1 || timeSinceLastSent < rateLimitMs);
if (willBeQueued) {
showQueueNotification(webhookUrl, webhookName);
}
processQueue(webhookUrl);
}
/**
* Processes the queue for a given webhook URL.
* It sends the next item in the queue, respecting the rate limit.
* If a rate limit is active and the last send was too recent, it schedules
* a retry using a timer.
*
* @param {string} webhookUrl - The URL of the webhook whose queue needs processing.
*/
function processQueue(webhookUrl) {
const queueData = webhookQueues.get(webhookUrl);
if (!queueData || queueData.queue.length === 0) return;
const now = Date.now();
const timeSinceLastSent = now - queueData.lastSent;
const rateLimitMs = queueData.rateLimit * 1000;
if (queueData.rateLimit > 0 && timeSinceLastSent < rateLimitMs) {
// Need to wait before sending
const waitTime = rateLimitMs - timeSinceLastSent;
if (queueData.timer) {
clearTimeout(queueData.timer);
}
queueData.timer = setTimeout(() => {
processQueue(webhookUrl);
}, waitTime);
return;
}
// Send the next item in queue
const item = queueData.queue.shift();
queueData.lastSent = now;
// Clear any existing queue notification for this webhook
clearQueueNotification(webhookUrl);
postToWebhookDirect(webhookUrl, item.payload, 3, item.webhookName);
// Schedule next item if queue has more items
if (queueData.queue.length > 0) {
if (queueData.rateLimit > 0) {
queueData.timer = setTimeout(() => {
processQueue(webhookUrl);
}, rateLimitMs);
} else {
// No rate limit, process immediately
processQueue(webhookUrl);
}
}
}
/**
* Sanitizes a string to be used as a Chrome context menu ID.
* Replaces non-alphanumeric characters with underscores and truncates to 50 characters.
*
* @param {string} name - The original string to sanitize.
* @returns {string} The sanitized string suitable for a menu ID.
*/
function sanitizeMenuId(name) {
return name.replace(/[^a-zA-Z0-9_-]/g, "_").substring(0, 50);
}
let updateWebhookMenusTimeout;
/**
* Updates the Chrome context menus with the currently configured webhooks.
* This function debounces multiple calls to avoid excessive menu rebuilds.
* It first removes all existing custom menu items, then recreates the parent
* "Send to Webhook" menu, and finally adds child menu items for each stored webhook.
*/
function updateWebhookMenus() {
// Debounce to avoid excessive rebuilds
clearTimeout(updateWebhookMenusTimeout);
updateWebhookMenusTimeout = setTimeout(() => {
// First remove all existing child items (if any)
chrome.contextMenus.removeAll(() => {
// Recreate parent menu to avoid reference errors
chrome.contextMenus.create(
{
id: "sendToWebhook",
title: "Send to Webhook",
contexts: ["page", "link", "image", "selection", "video"],
},
() => {
// Check for errors
if (chrome.runtime.lastError) {
console.error(
`Error recreating parent menu: ${chrome.runtime.lastError.message}`,
);
return;
}
// Now add child items
chrome.storage.local.get("webhooks", (data) => {
if (data.webhooks && data.webhooks.length > 0) {
data.webhooks.forEach((webhook, index) => {
const sanitizedId = sanitizeMenuId(webhook.name);
// Create menu item for page, link, and image contexts
chrome.contextMenus.create({
id: `sendTo_${sanitizedId}_${index}_normal`,
parentId: "sendToWebhook",
title: webhook.name,
contexts: ["page", "link", "image", "video"],
});
// Create separate menu item for selection context
chrome.contextMenus.create({
id: `sendTo_${sanitizedId}_${index}_selection`,
parentId: "sendToWebhook",
title: webhook.name,
contexts: ["selection"],
});
});
}
});
},
);
});
}, 100);
}
chrome.contextMenus.onClicked.addListener((info, tab) => {
if (info.menuItemId.startsWith("sendTo_")) {
chrome.storage.local.get(["webhooks", "settings"], (data) => {
// Extract index from menu ID (sendTo_sanitizedName_index_type)
const parts = info.menuItemId.split("_");
const indexPart = parts[parts.length - 2]; // Second to last part is the index
const index = parseInt(indexPart, 10);
const webhook = data.webhooks[index];
if (webhook) {
const hasCustomFields = Array.isArray(webhook.customFields);
if (hasCustomFields) {
// Store data needed for sending the webhook later
const pendingWebhook = {
webhook,
info,
tabId: tab.id,
};
// Get screen resolution and window size from the tab
chrome.scripting.executeScript({
target: { tabId: tab.id },
func: () => ({
screenWidth: window.screen.width,
screenHeight: window.screen.height,
windowWidth: window.innerWidth,
windowHeight: window.innerHeight,
}),
}).then((results) => {
const screenData = results?.[0]?.result || {
screenWidth: null,
screenHeight: null,
windowWidth: null,
windowHeight: null,
};
chrome.runtime.getPlatformInfo((platformInfo) => {
const browserInfo = navigator.userAgent;
const os = platformInfo.os || "Unknown OS";
const browserVersion = browserInfo.match(/(Chrome)\/([0-9.]+)/)
? `${browserInfo.match(/(Chrome)\/([0-9.]+)/)[0]}`
: browserInfo;
// Simple device type detection (can be more robust if needed)
const deviceType =
navigator.userAgent.match(/Mobi/) ||
navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/iPhone|iPad|iPod/i)
? "Mobile"
: screenData.screenWidth && screenData.screenWidth <= 768
? "Tablet"
: "Desktop";
pendingWebhook.browserInfo = {
browser: browserVersion,
operatingSystem: os,
deviceType: deviceType,
screenResolution: screenData.screenWidth
? `${screenData.screenWidth}x${screenData.screenHeight}`
: null,
windowSize: screenData.windowWidth
? `${screenData.windowWidth}x${screenData.windowHeight}`
: null,
};
chrome.storage.local.set({ pendingWebhook }, () => {
// Open the modal window
chrome.windows.create({
url: "modal.html",
type: "popup",
width: 500,
height: 600,
});
});
});
});
} else {
// Send webhook directly without showing modal
let urlToSend,
type,
selectionText = null;
if (info.linkUrl) {
urlToSend = info.linkUrl;
type = "link";
} else if (info.srcUrl) {
urlToSend = info.srcUrl;
type = info.mediaType === "video" ? "video" : "image";
} else {
type = info.selectionText ? "selection" : "page";
urlToSend = info.pageUrl;
selectionText = info.selectionText;
}
extractDataAndSend(
webhook.url,
urlToSend,
type,
tab.id,
selectionText,
"",
info.pageUrl,
);
}
}
});
}
});
// Listener for messages from the modal
chrome.runtime.onMessage.addListener((request, _sender, sendResponse) => {
if (request.type === "sendWebhookWithCustomFields") {
chrome.storage.local.get("pendingWebhook", (data) => {
if (data.pendingWebhook) {
const { webhook, info, tabId } = data.pendingWebhook;
const customFields = request.customFields;
// Determine context and extract data
if (info.linkUrl) {
extractDataAndSend(
webhook.url,
info.linkUrl,
"link",
tabId,
null,
customFields,
info.pageUrl,
);
} else if (info.srcUrl) {
extractDataAndSend(
webhook.url,
info.srcUrl,
info.mediaType === "video" ? "video" : "image",
tabId,
null,
customFields,
info.pageUrl,
);
} else {
const type = info.selectionText ? "selection" : "page";
extractDataAndSend(
webhook.url,
info.pageUrl,
type,
tabId,
info.selectionText,
customFields,
info.pageUrl,
);
}
// Clean up the stored data
chrome.storage.local.remove("pendingWebhook");
sendResponse({ status: "sent" });
}
});
} else if (request.type === "modalCanceled") {
// Clean up the stored data if the user cancels
chrome.storage.local.remove("pendingWebhook", () => {
// This callback ensures storage is cleared before we respond
sendResponse({ status: "canceled" });
});
}
return true; // Crucial for async sendResponse
});
/**
* Extracts relevant data from the current tab based on the context type
* (page, link, image, video, selection) and then sends it to the specified webhook.
* It uses `chrome.scripting.executeScript` to get page-specific details.
*
* @param {string} webhookUrl - The URL of the webhook to send data to.
* @param {string} urlToSend - The URL related to the context (e.g., page URL, link URL, image URL).
* @param {'page'|'link'|'image'|'video'|'selection'} type - The context type of the data.
* @param {number} tabId - The ID of the tab where the action originated.
* @param {string|null} selectionText - The selected text, if the context is 'selection'.
* @param {Object} customFields - Any additional user-provided content from the custom fields.
* @param {string} pageUrl - The URL of the page where the context menu was clicked.
*/
function extractDataAndSend(
webhookUrl,
urlToSend,
type,
tabId,
selectionText,
customFields,
pageUrl,
) {
let codeToExecute;
// Function to get screen resolution, executed in content script
const getScreenResolution = () => ({
screenWidth: window.screen.width,
screenHeight: window.screen.height,
});
// Function to get browser window size, executed in content script
const getWindowSize = () => ({
windowWidth: window.innerWidth,
windowHeight: window.innerHeight,
});
if (type === "page" || type === "selection") {
codeToExecute = () => ({
title: document.title,
description:
document
.querySelector('meta[name="description"]')
?.getAttribute("content") || null,
keywords:
document
.querySelector('meta[name="keywords"]')
?.getAttribute("content") || null,
favicon:
document.querySelector('link[rel="icon"]')?.href ||
document.querySelector('link[rel="shortcut icon"]')?.href ||
null,
});
} else if (type === "link") {
codeToExecute = (...rest) => {
let linkTitle = null;
const links = document.querySelectorAll("a");
for (const link of links) {
if (link.href === rest[0]) {
linkTitle =
link.title ||
link.getAttribute("aria-label") ||
link.innerText ||
null;
}
}
return {
title: document.title,
description:
document
.querySelector('meta[name="description"]')
?.getAttribute("content") || null,
keywords:
document
.querySelector('meta[name="keywords"]')
?.getAttribute("content") || null,
favicon:
document.querySelector('link[rel="icon"]')?.href ||
document.querySelector('link[rel="shortcut icon"]')?.href ||
null,
linkTitle,
};
};
} else if (type === "image") {
codeToExecute = (...rest) => {
let altText = null;
const media = document.querySelectorAll("img");
for (const item of media) {
if (item.src === rest[0]) {
altText = item.alt || item.title || null;
}
}
return {
title: document.title,
description:
document
.querySelector('meta[name="description"]')
?.getAttribute("content") || null,
keywords:
document
.querySelector('meta[name="keywords"]')
?.getAttribute("content") || null,
favicon:
document.querySelector('link[rel="icon"]')?.href ||
document.querySelector('link[rel="shortcut icon"]')?.href ||
null,
altText,
};
};
} else if (type === "video") {
codeToExecute = (...rest) => {
let altText = null;
const media = document.querySelectorAll("video");
for (const item of media) {
if (item.src === rest[0]) {
altText = item.alt || item.title || null;
}
}
return {
title: document.title,
description:
document
.querySelector('meta[name="description"]')
?.getAttribute("content") || null,
keywords:
document
.querySelector('meta[name="keywords"]')
?.getAttribute("content") || null,
favicon:
document.querySelector('link[rel="icon"]')?.href ||
document.querySelector('link[rel="shortcut icon"]')?.href ||
null,
altText,
};
};
}
// Execute scripts: one for page data, one for screen resolution, and one for window size
Promise.all([
chrome.scripting.executeScript({
target: { tabId: tabId },
func: codeToExecute,
args: [urlToSend],
}),
chrome.scripting.executeScript({
target: { tabId: tabId },
func: getScreenResolution,
}),
chrome.scripting.executeScript({
target: { tabId: tabId },
func: getWindowSize,
}),
]).then(([injectionResults, resolutionResults, windowResults]) => {
if (chrome.runtime.lastError) {
console.error(
"Script injection failed:",
chrome.runtime.lastError.message,
);
}
const extractedData = injectionResults?.[0]
? injectionResults[0].result
: null;
const screenResolution = resolutionResults?.[0]
? resolutionResults[0].result
: { screenWidth: null, screenHeight: null };
const windowSize = windowResults?.[0]
? windowResults[0].result
: { windowWidth: null, windowHeight: null };
// Get browser, OS, and device type using chrome.runtime and navigator.userAgent
chrome.runtime.getPlatformInfo((platformInfo) => {
const browserInfo = navigator.userAgent;
const os = platformInfo.os || "Unknown OS";
const browserVersion = browserInfo.match(/(Chrome)\/([0-9.]+)/)
? `${browserInfo.match(/(Chrome)\/([0-9.]+)/)[0]}`
: browserInfo; // Fallback to full user agent if Chrome version not found
// Simple device type detection (can be more robust if needed)
const deviceType =
navigator.userAgent.match(/Mobi/) ||
navigator.userAgent.match(/Android/i) ||
navigator.userAgent.match(/iPhone|iPad|iPod/i)
? "Mobile"
: screenResolution.screenWidth && screenResolution.screenWidth <= 768
? "Tablet"
: "Desktop";
// Find webhook name for notification
chrome.storage.local.get("webhooks", (data) => {
const webhook = data.webhooks?.find((wh) => wh.url === webhookUrl);
const webhookName = webhook ? webhook.name : "Webhook";
// Build enhanced payload
const payload = {
url: urlToSend,
pageUrl,
type,
timestamp: new Date().toISOString(),
title: extractedData?.title || null,
description: extractedData?.description || null,
keywords: extractedData?.keywords || null,
favicon: extractedData?.favicon || null,
linkTitle: extractedData?.linkTitle || null,
altText: extractedData?.altText || null,
customFields: customFields ?? null,
selectedText: selectionText,
browser: browserVersion,
operatingSystem: os,
deviceType: deviceType,
screenResolution: screenResolution.screenWidth
? `${screenResolution.screenWidth}x${screenResolution.screenHeight}`
: null,
windowSize: windowSize.windowWidth
? `${windowSize.windowWidth}x${windowSize.windowHeight}`
: null,
};
// Find webhook to get rate limit
chrome.storage.local.get("webhooks", (webhooksData) => {
const webhook = webhooksData.webhooks?.find(
(wh) => wh.url === webhookUrl,
);
const rateLimit = webhook ? webhook.rateLimit || 0 : 0;
addToQueue(webhookUrl, payload, webhookName, rateLimit);
});
});
});
});
}
/**
* Displays a basic Chrome notification.
*
* @param {string} title - The title of the notification.
* @param {string} message - The main message content of the notification.
* @param {boolean} [isSuccess=true] - Whether the notification indicates success (influences icon, if different).
*/
function showNotification(title, message, isSuccess = true) {
const iconPath = isSuccess ? "images/icon48.png" : "images/icon48.png"; // Currently same icon for success/failure
chrome.notifications.create({
type: "basic",
iconUrl: iconPath,
title: title,
message: message,
});
}
/**
* Displays and updates a dynamic Chrome notification for a webhook queue.
* This notification shows the number of items in the queue and estimated time remaining.
* It updates at a configurable interval and auto-clears after 60 seconds.
*
* @param {string} webhookUrl - The URL of the webhook associated with the queue.
* @param {string} webhookName - The name of the webhook for display in the notification.
*/
function showQueueNotification(webhookUrl, webhookName) {
const notificationId = `queue_${webhookUrl}_${Date.now()}`;
// Clear any existing notification for this webhook
clearQueueNotification(webhookUrl);
// Get notification interval from settings
chrome.storage.local.get(
{ settings: { notificationInterval: 5 } },
(data) => {
const updateIntervalMs = data.settings.notificationInterval * 1000;
function updateNotification() {
const queueData = webhookQueues.get(webhookUrl);
if (!queueData || queueData.queue.length === 0) {
clearQueueNotification(webhookUrl);
return;
}
const now = Date.now();
const timeSinceLastSent = now - queueData.lastSent;
const rateLimitMs = queueData.rateLimit * 1000;
const waitTime = Math.max(0, rateLimitMs - timeSinceLastSent);
const queuePosition = queueData.queue.length;
const totalWait = Math.ceil(
(waitTime + (queuePosition - 1) * rateLimitMs) / 1000,
);
chrome.notifications.create(notificationId, {
type: "basic",
iconUrl: "images/icon48.png",
title: `⏳ ${webhookName} - Queued`,
message: `${queuePosition} in queue, ~${totalWait}s remaining`,
});
}
// Initial notification
updateNotification();
// Update at configured interval
const intervalId = setInterval(updateNotification, updateIntervalMs);
queueNotifications.set(webhookUrl, { notificationId, intervalId });
// Auto-clear after 60 seconds to prevent indefinite notifications
setTimeout(() => clearQueueNotification(webhookUrl), 60000);
},
);
}
/**
* Clears a specific queue notification and its associated update interval.
*
* @param {string} webhookUrl - The URL of the webhook whose queue notification should be cleared.
*/
function clearQueueNotification(webhookUrl) {
const notification = queueNotifications.get(webhookUrl);
if (notification) {
clearInterval(notification.intervalId);
chrome.notifications.clear(notification.notificationId);
queueNotifications.delete(webhookUrl);
}
}
/**
* Sends a POST request to a webhook URL with a JSON payload.
* Includes retry logic for failed requests.
* Displays success or failure notifications upon completion.
*
* @param {string} webhookUrl - The URL of the webhook.
* @param {object} payload - The JSON payload to send.
* @param {number} [retryCount=3] - The number of retries remaining.
* @param {string} [webhookName="Webhook"] - The name of the webhook for notifications.
*/
function postToWebhookDirect(
webhookUrl,
payload,
retryCount = 3,
webhookName = "Webhook",
) {
fetch(webhookUrl, {
method: "POST",
headers: {
"Content-Type": "application/json",
},
body: JSON.stringify(payload),
})
.then((response) => {
if (!response.ok && retryCount > 0) {
console.log(
`Webhook failed with status ${response.status}, retrying... (${retryCount} attempts left)`,
);
setTimeout(
() =>
postToWebhookDirect(
webhookUrl,
payload,
retryCount - 1,
webhookName,
),
1000,
);
} else if (response.ok) {
console.log("Webhook sent with response status:", response.status);
showNotification(
`✅ ${webhookName} - Success`,
`Data sent successfully to ${webhookName}`,
true,
);
} else {
console.log("Webhook failed after all retries");
showNotification(
`❌ ${webhookName} - Failed`,
`Failed to send data after 3 attempts`,
false,
);
}
})
.catch((error) => {
console.error("Error sending webhook:", error);
if (retryCount > 0) {
console.log(
`Retrying webhook in 2 seconds... (${retryCount} attempts left)`,
);
setTimeout(
() =>
postToWebhookDirect(
webhookUrl,
payload,
retryCount - 1,
webhookName,
),
2000,
);
} else {
showNotification(
`❌ ${webhookName} - Error`,
`Network error: ${error.message}`,
false,
);
}
});
}
// Listen for changes in the webhooks data to update context menus and queues
chrome.storage.onChanged.addListener((changes, namespace) => {
if (namespace === "local" && changes.webhooks) {
updateWebhookMenus();
initializeQueues();
}
});