Skip to content

Commit bb5d7cb

Browse files
committed
Add missing message handlers to background.js and fix sync errors
Fixed 'message port closed' error by adding handlers to the ACTUAL background script: - Added syncInventoryAllTabs handler (was only in unused simpleBackground.js) - Added triggerFullSync handler to background.js - Added extension context validation in transactionMonitor.js Clarified background script situation: - manifest.json uses background.js (line 36) - simpleBackground.js is NOT used (dead code) - All handlers now in correct file (background.js) Next step: Delete simpleBackground.js to clean up codebase
1 parent cfaf146 commit bb5d7cb

3 files changed

Lines changed: 136 additions & 45 deletions

File tree

background.js

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1710,6 +1710,91 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
17101710
return true; // Keep channel open for async response
17111711
}
17121712

1713+
// Handle inventory sync request - broadcast to all tabs
1714+
if (request.action === 'syncInventoryAllTabs') {
1715+
console.log('[Background] Broadcasting inventory sync to all tabs');
1716+
1717+
chrome.tabs.query({}, (tabs) => {
1718+
let synced = false;
1719+
tabs.forEach(tab => {
1720+
// Only send to inventory pages
1721+
if (tab.url && tab.url.includes('steamcommunity.com') && tab.url.includes('inventory')) {
1722+
console.log('[Background] Sending sync message to tab:', tab.id);
1723+
chrome.tabs.sendMessage(tab.id, { type: 'CS2_SYNC_INVENTORY' }, (response) => {
1724+
if (!chrome.runtime.lastError) {
1725+
console.log('[Background] Sync triggered on tab:', tab.id, response);
1726+
synced = true;
1727+
}
1728+
});
1729+
}
1730+
});
1731+
1732+
// If no inventory tab is open, just acknowledge
1733+
sendResponse({ success: true, synced: synced });
1734+
});
1735+
1736+
return true; // Keep message channel open
1737+
}
1738+
1739+
// Handle full sync request (transaction + inventory)
1740+
if (request.action === 'triggerFullSync') {
1741+
console.log('[Background] Triggering full sync (transaction + inventory)...');
1742+
1743+
(async () => {
1744+
try {
1745+
// Trigger inventory sync on inventory tabs
1746+
console.log('[Background] Syncing inventory...');
1747+
const tabs = await chrome.tabs.query({});
1748+
const inventoryTabs = tabs.filter(tab =>
1749+
tab.url && tab.url.includes('steamcommunity.com') && tab.url.includes('inventory')
1750+
);
1751+
1752+
if (inventoryTabs.length > 0) {
1753+
// Send sync message to existing inventory tabs
1754+
inventoryTabs.forEach(tab => {
1755+
chrome.tabs.sendMessage(tab.id, { type: 'CS2_SYNC_INVENTORY' }, (response) => {
1756+
if (!chrome.runtime.lastError) {
1757+
console.log('[Background] Inventory sync triggered on tab:', tab.id);
1758+
}
1759+
});
1760+
});
1761+
} else {
1762+
// Open inventory in background tab and trigger sync
1763+
console.log('[Background] Opening inventory tab...');
1764+
chrome.tabs.create({
1765+
url: 'https://steamcommunity.com/my/inventory/#730',
1766+
active: false
1767+
}, (tab) => {
1768+
// Wait for page to load
1769+
setTimeout(() => {
1770+
chrome.tabs.sendMessage(tab.id, { type: 'CS2_SYNC_INVENTORY' }, (response) => {
1771+
if (!chrome.runtime.lastError) {
1772+
console.log('[Background] Inventory sync triggered on new tab');
1773+
}
1774+
});
1775+
}, 3000);
1776+
});
1777+
}
1778+
1779+
// Respond quickly to avoid port closure
1780+
// Transactions sync automatically via alarm (every 60s)
1781+
sendResponse({
1782+
success: true,
1783+
message: 'Inventory sync triggered. Transactions sync automatically every 60 seconds.'
1784+
});
1785+
1786+
} catch (error) {
1787+
console.error('[Background] Full sync failed:', error);
1788+
sendResponse({
1789+
success: false,
1790+
error: error.message
1791+
});
1792+
}
1793+
})();
1794+
1795+
return true; // Keep message channel open for async response
1796+
}
1797+
17131798
return false;
17141799
});
17151800

src/simpleBackground.js

Lines changed: 9 additions & 28 deletions
Original file line numberDiff line numberDiff line change
@@ -476,28 +476,8 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
476476

477477
(async () => {
478478
try {
479-
const results = {
480-
transaction: false,
481-
inventory: false
482-
};
483-
484-
// Step 1: Sync pending transactions
485-
console.log('[Background] Step 1/2: Syncing pending transactions...');
486-
const transactionResult = await chrome.storage.local.get(['pendingTransactions']);
487-
const pendingTransactions = transactionResult.pendingTransactions || [];
488-
489-
if (pendingTransactions.length > 0) {
490-
// Process all pending transactions
491-
await processTransactionQueue();
492-
results.transaction = true;
493-
console.log('[Background] ✅ Pending transactions synced');
494-
} else {
495-
console.log('[Background] No pending transactions to sync');
496-
results.transaction = true; // Not an error, just nothing to sync
497-
}
498-
499-
// Step 2: Sync inventory
500-
console.log('[Background] Step 2/2: Syncing inventory...');
479+
// Step 1: Trigger inventory sync
480+
console.log('[Background] Syncing inventory...');
501481
const inventoryTabs = await new Promise((resolve) => {
502482
chrome.tabs.query({}, (tabs) => {
503483
const inventoryTabs = tabs.filter(tab =>
@@ -507,13 +487,15 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
507487
});
508488
});
509489

490+
let inventorySynced = false;
491+
510492
if (inventoryTabs.length > 0) {
511493
// Send sync message to inventory tabs
512494
for (const tab of inventoryTabs) {
513495
chrome.tabs.sendMessage(tab.id, { type: 'CS2_SYNC_INVENTORY' }, (response) => {
514496
if (!chrome.runtime.lastError) {
515497
console.log('[Background] Inventory sync triggered on tab:', tab.id);
516-
results.inventory = true;
498+
inventorySynced = true;
517499
}
518500
});
519501
}
@@ -529,21 +511,20 @@ chrome.runtime.onMessage.addListener((request, sender, sendResponse) => {
529511
chrome.tabs.sendMessage(tab.id, { type: 'CS2_SYNC_INVENTORY' }, (response) => {
530512
if (!chrome.runtime.lastError) {
531513
console.log('[Background] Inventory sync triggered on new tab');
532-
results.inventory = true;
514+
inventorySynced = true;
533515
}
534516
});
535517
}, 3000); // Wait 3 seconds for inventory to load
536518
});
537519
}
538520

539-
// Wait a bit for inventory sync to complete
521+
// Wait a bit for inventory sync to start
540522
setTimeout(() => {
541523
sendResponse({
542524
success: true,
543-
results: results,
544-
message: 'Full sync completed'
525+
message: 'Sync triggered successfully'
545526
});
546-
}, 2000);
527+
}, 500);
547528

548529
} catch (error) {
549530
console.error('[Background] Full sync failed:', error);

src/transactionMonitor.js

Lines changed: 42 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -548,13 +548,17 @@ function addSyncToDashboardButton() {
548548
syncButton.innerHTML = '<span>❌ Sync Failed</span>';
549549
syncButton.style.background = 'linear-gradient(135deg, #ef4444, #dc2626) !important';
550550

551-
// Show error notification
551+
// Show error notification with appropriate message
552+
const errorMessage = error.message?.includes('invalidated')
553+
? 'Extension was reloaded. Please refresh this page and try again.'
554+
: 'Please try again or sync manually from the popup';
555+
552556
showNotification(
553557
'❌ Sync Failed',
554-
'Please try again or sync manually from the popup',
558+
errorMessage,
555559
'linear-gradient(135deg, #ef4444, #dc2626)',
556560
null,
557-
4000
561+
5000
558562
);
559563

560564
// Reset button after 3 seconds
@@ -586,21 +590,30 @@ function addSyncToDashboardButton() {
586590
async function triggerFullSync() {
587591
console.log('[Transaction Monitor] Triggering full sync (transaction + inventory)...');
588592

593+
// Check if extension context is valid
594+
if (!chrome?.runtime?.id) {
595+
throw new Error('Extension context invalidated. Please reload the page.');
596+
}
597+
589598
return new Promise((resolve, reject) => {
590-
// Send message to background script to trigger both syncs
591-
chrome.runtime.sendMessage({
592-
action: 'triggerFullSync'
593-
}, (response) => {
594-
if (chrome.runtime.lastError) {
595-
console.error('[Transaction Monitor] Full sync error:', chrome.runtime.lastError);
596-
reject(new Error(chrome.runtime.lastError.message));
597-
} else if (response && response.success) {
598-
console.log('[Transaction Monitor] Full sync completed:', response);
599-
resolve(response);
600-
} else {
601-
reject(new Error(response?.error || 'Sync failed'));
602-
}
603-
});
599+
try {
600+
// Send message to background script to trigger both syncs
601+
chrome.runtime.sendMessage({
602+
action: 'triggerFullSync'
603+
}, (response) => {
604+
if (chrome.runtime.lastError) {
605+
console.error('[Transaction Monitor] Full sync error:', chrome.runtime.lastError);
606+
reject(new Error(chrome.runtime.lastError.message));
607+
} else if (response && response.success) {
608+
console.log('[Transaction Monitor] Full sync completed:', response);
609+
resolve(response);
610+
} else {
611+
reject(new Error(response?.error || 'Sync failed'));
612+
}
613+
});
614+
} catch (error) {
615+
reject(new Error('Extension context invalidated. Please reload the page.'));
616+
}
604617
});
605618
}
606619

@@ -652,6 +665,12 @@ async function triggerInventorySync() {
652665
*/
653666
async function saveTransactionToStorage(transaction, status = 'pending') {
654667
try {
668+
// Check if extension context is valid
669+
if (!chrome?.storage?.local) {
670+
console.error('[Transaction Monitor] Extension context invalidated, cannot save to storage');
671+
return null;
672+
}
673+
655674
const result = await chrome.storage.local.get(['pendingTransactions']);
656675
const transactions = result.pendingTransactions || [];
657676

@@ -681,6 +700,12 @@ async function saveTransactionToStorage(transaction, status = 'pending') {
681700
*/
682701
async function updateTransactionStatus(transactionId, status) {
683702
try {
703+
// Check if extension context is valid
704+
if (!chrome?.storage?.local) {
705+
console.error('[Transaction Monitor] Extension context invalidated, cannot update storage');
706+
return;
707+
}
708+
684709
const result = await chrome.storage.local.get(['pendingTransactions']);
685710
const transactions = result.pendingTransactions || [];
686711

0 commit comments

Comments
 (0)