fix: comprehensive extension context invalidated handling
Some checks failed
CI — Test & Build / Test & Build (push) Has been cancelled

This commit is contained in:
Forge
2026-03-06 13:56:30 +08:00
parent 4343abbab3
commit a0b00c6d87
3 changed files with 93 additions and 9 deletions

View File

@@ -204,7 +204,7 @@ export default defineContentScript({
function isExtensionValid(): boolean {
try {
return !!chrome.runtime?.id;
return typeof chrome !== 'undefined' && !!chrome.runtime?.id;
} catch {
return false;
}
@@ -223,6 +223,25 @@ export default defineContentScript({
setTimeout(() => toast.remove(), 4000);
}
// ─── Safe chrome.runtime.sendMessage wrapper ──────────────────────────────
async function safeSendMessage(payload: Record<string, unknown>): Promise<unknown> {
if (!isExtensionValid()) {
showErrorToast('LexAI was updated — please refresh this page.');
return null;
}
try {
return await chrome.runtime.sendMessage(payload);
} catch (err) {
if (String(err).includes('Extension context invalidated') ||
String(err).includes('message channel closed')) {
showErrorToast('LexAI was updated — please refresh this page.');
hideToolbar();
}
return null;
}
}
// ─── LLM call ─────────────────────────────────────────────────────────────
async function runAction(action: string) {
@@ -251,13 +270,15 @@ export default defineContentScript({
}
try {
const response = await chrome.runtime.sendMessage({
const response = await safeSendMessage({
type: 'ANALYZE_TEXT',
payload: { text: textToProcess, action },
});
}) as { error?: string; result?: string } | null;
hideToolbar();
if (response === null) return; // safeSendMessage already handled the error
if (response?.error) {
showModal(`${response.error}`, null);
} else {
@@ -265,8 +286,9 @@ export default defineContentScript({
}
} catch (err) {
hideToolbar();
if (String(err).includes('Extension context invalidated')) {
showErrorToast('LexAI was updated. Please refresh the page.');
if (String(err).includes('Extension context invalidated') ||
String(err).includes('message channel closed')) {
showErrorToast('LexAI was updated — please refresh this page.');
} else {
showModal(`❌ Error: ${String(err)}`, null);
}
@@ -440,6 +462,25 @@ export default defineContentScript({
document.body.appendChild(modal);
}
// ─── Global extension context error handlers ──────────────────────────────
window.addEventListener('error', (e) => {
if (e.message?.includes('Extension context invalidated')) {
e.preventDefault(); // suppress console error
hideToolbar();
showErrorToast('LexAI was updated — please refresh this page.');
}
});
window.addEventListener('unhandledrejection', (e) => {
if (String(e.reason)?.includes('Extension context invalidated') ||
String(e.reason)?.includes('message channel closed')) {
e.preventDefault();
hideToolbar();
showErrorToast('LexAI was updated — please refresh this page.');
}
});
// ─── Event listeners ──────────────────────────────────────────────────────
document.addEventListener('mouseup', (e) => {