Skip to content

Commit cd54512

Browse files
committed
catch error when ethereum provider is set before our attempt to set
1 parent f0ca94b commit cd54512

2 files changed

Lines changed: 30 additions & 2 deletions

File tree

src/initializeInpageProvider.test.ts

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,27 @@ describe('setGlobalProvider', () => {
2020
new Event('ethereum#initialized'),
2121
);
2222
});
23+
24+
it('should not throw an error if the global ethereum provider is already set', () => {
25+
const errorSpy = jest.spyOn(console, 'error');
26+
27+
const mockProvider = {} as unknown as MetaMaskInpageProvider;
28+
Object.defineProperty(window, 'ethereum', {
29+
get() {
30+
return {};
31+
},
32+
set() {
33+
throw new Error('window.ethereum already set');
34+
},
35+
configurable: false,
36+
});
37+
expect(() => setGlobalProvider(mockProvider)).not.toThrow();
38+
39+
expect(errorSpy).toHaveBeenCalledWith(
40+
'MetaMask encountered an error setting the global Ethereum provider - this is likely due to another Ethereum wallet extension also setting the global Ethereum provider:',
41+
expect.any(Error),
42+
);
43+
});
2344
});
2445

2546
describe('announceCaip294WalletData', () => {

src/initializeInpageProvider.ts

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -98,8 +98,15 @@ export function initializeProvider({
9898
export function setGlobalProvider(
9999
providerInstance: MetaMaskInpageProvider,
100100
): void {
101-
(window as Record<string, any>).ethereum = providerInstance;
102-
window.dispatchEvent(new Event('ethereum#initialized'));
101+
try {
102+
(window as Record<string, any>).ethereum = providerInstance;
103+
window.dispatchEvent(new Event('ethereum#initialized'));
104+
} catch (error) {
105+
console.error(
106+
'MetaMask encountered an error setting the global Ethereum provider - this is likely due to another Ethereum wallet extension also setting the global Ethereum provider:',
107+
error,
108+
);
109+
}
103110
}
104111

105112
/**

0 commit comments

Comments
 (0)