Skip to content

Commit 246fdeb

Browse files
committed
refactor: add robust message handling for InjectScriptV2
- Introduce `getBrowser` utility to determine runtime environment (Chrome/Firefox API). - Add `sendMessage` helper function for safe and consistent message dispatching. - Replace direct `chrome.runtime.sendMessage` calls with `sendMessage` for error resilience. - Improve error handling with detailed console logs for runtime and unexpected exceptions.
1 parent 481e1a1 commit 246fdeb

1 file changed

Lines changed: 31 additions & 1 deletion

File tree

src/InjectScriptV2.ts

Lines changed: 31 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -115,6 +115,36 @@ export default class extends AbstractInjectScript {
115115

116116
protected generateCode(): (type: string, func: (...args: any[]) => any, args: any[]) => void {
117117
return (type: string, func: (...args: any[]) => any, args: any[]): void => {
118+
const getBrowser = (): typeof chrome | undefined => {
119+
const api = globalThis?.browser?.runtime?.id ? globalThis.browser : globalThis.chrome;
120+
121+
return api?.runtime ? api : undefined;
122+
};
123+
124+
const sendMessage = (message: any): void => {
125+
const browser = getBrowser();
126+
127+
if (!browser) {
128+
return;
129+
}
130+
131+
try {
132+
browser.runtime.sendMessage(message, () => {
133+
const error = browser.runtime.lastError;
134+
135+
if (error) {
136+
console.error(
137+
`Failed to send a message from the injected script: ${error?.message ?? "unknown error"}`
138+
);
139+
}
140+
});
141+
} catch (e) {
142+
console.error(
143+
`Unexpected exception during message dispatch from injected context: ${e instanceof Error ? e.message : String(e)}`
144+
);
145+
}
146+
};
147+
118148
const data: Record<string, unknown> = {};
119149

120150
Promise.resolve()
@@ -130,7 +160,7 @@ export default class extends AbstractInjectScript {
130160
};
131161
})
132162
.finally(() => {
133-
chrome.runtime.sendMessage({type, data});
163+
sendMessage({type, data});
134164
});
135165
};
136166
}

0 commit comments

Comments
 (0)