fix(content-script-context): handle undefined browser.runtime (#2042)

This commit is contained in:
Mark
2026-02-05 18:17:16 -05:00
committed by GitHub
parent 48891a7ca5
commit f3834ac0e2
2 changed files with 20 additions and 1 deletions
@@ -32,6 +32,25 @@ describe('Content Script Context', () => {
expect(isValid).toBe(false);
});
it('should not throw when browser.runtime is undefined (extension context fully invalidated)', () => {
const ctx = new ContentScriptContext('test');
const onInvalidated = vi.fn();
ctx.onInvalidated(onInvalidated);
// Simulate complete extension context invalidation where browser.runtime becomes undefined
const originalRuntime = fakeBrowser.runtime;
// @ts-ignore
fakeBrowser.runtime = undefined;
// Should not throw, and should mark as invalid
expect(() => ctx.isInvalid).not.toThrow();
expect(ctx.isInvalid).toBe(true);
expect(onInvalidated).toBeCalled();
// Restore for other tests
fakeBrowser.runtime = originalRuntime;
});
it('should invalidate the current content script when a new context is created', async () => {
const name = 'test';
const onInvalidated = vi.fn();
@@ -71,7 +71,7 @@ export class ContentScriptContext implements AbortController {
}
get isInvalid(): boolean {
if (browser.runtime.id == null) {
if (browser.runtime?.id == null) {
this.notifyInvalidated(); // Sets `signal.aborted` to true
}
return this.signal.aborted;