|
62 | 62 | source: 'popup' |
63 | 63 | }; |
64 | 64 |
|
65 | | - // Try to send message, and if it fails, inject the content script programmatically |
| 65 | + // First, always try to inject the content script to ensure it's loaded |
| 66 | + // This handles cases where manifest injection failed or page was already loaded |
| 67 | + try { |
| 68 | + await chrome.scripting.executeScript({ |
| 69 | + target: { tabId: activeTab.id }, |
| 70 | + files: ['content.js'] |
| 71 | + }); |
| 72 | + |
| 73 | + // Small delay to ensure script initializes |
| 74 | + await new Promise(resolve => setTimeout(resolve, 100)); |
| 75 | + } catch (injectErr) { |
| 76 | + // Injection might fail if script is already injected, that's okay |
| 77 | + console.log('Content script injection attempted:', injectErr.message); |
| 78 | + } |
| 79 | + |
| 80 | + // Now try to send the message |
66 | 81 | let response; |
67 | 82 | try { |
68 | 83 | response = await chrome.tabs.sendMessage(activeTab.id, message); |
69 | 84 | } catch (err) { |
70 | | - // Handle Chrome messaging errors by injecting content script |
71 | | - if (err.message?.includes('Could not establish connection') || |
72 | | - err.message?.includes('Receiving end does not exist')) { |
73 | | - |
74 | | - console.log('Content script not ready, injecting programmatically...'); |
75 | | - |
76 | | - // Inject the content script |
77 | | - try { |
78 | | - await chrome.scripting.executeScript({ |
79 | | - target: { tabId: activeTab.id }, |
80 | | - files: ['content.js'] |
81 | | - }); |
82 | | - |
83 | | - // Wait a moment for script to initialize |
84 | | - await new Promise(resolve => setTimeout(resolve, 500)); |
85 | | - |
86 | | - // Try the message again |
87 | | - response = await chrome.tabs.sendMessage(activeTab.id, message); |
88 | | - } catch (injectError) { |
89 | | - console.error('Failed to inject content script:', injectError); |
90 | | - throw new Error('Unable to inject content script. Please refresh the page and try again.'); |
91 | | - } |
92 | | - } else { |
93 | | - throw err; |
| 85 | + // If still failing, try one more time with a longer delay |
| 86 | + console.log('First message failed, retrying with delay...'); |
| 87 | + await new Promise(resolve => setTimeout(resolve, 500)); |
| 88 | + |
| 89 | + try { |
| 90 | + response = await chrome.tabs.sendMessage(activeTab.id, message); |
| 91 | + } catch (finalErr) { |
| 92 | + console.error('All communication attempts failed:', finalErr); |
| 93 | + throw new Error('Unable to communicate with page. Please refresh and try again.'); |
94 | 94 | } |
95 | 95 | } |
96 | 96 |
|
|
0 commit comments