smesh-signer-content-script.ts raw
1 import browser from 'webextension-polyfill';
2 import { BackgroundRequestMessage } from './background-common';
3
4 // Inject the script that will provide window.nostr
5 // The script needs to run before any other scripts from the real
6 // page run (and maybe check for window.nostr).
7 const script = document.createElement('script');
8 script.setAttribute('async', 'false');
9 script.setAttribute('type', 'text/javascript');
10 script.setAttribute('src', browser.runtime.getURL('smesh-signer-extension.js'));
11 (document.head || document.documentElement).appendChild(script);
12
13 // listen for messages from that script
14 window.addEventListener('message', async (message) => {
15 // We will also receive our own messages, that we sent.
16 // We have to ignore them (they will not have a params field).
17
18 if (message.source !== window) return;
19 if (!message.data) return;
20 if (!message.data.params) return;
21 if (message.data.ext !== 'smesh-signer') return;
22
23 // pass on to background
24 let response;
25 try {
26 const request: BackgroundRequestMessage = {
27 method: message.data.method,
28 params: message.data.params,
29 host: location.host,
30 };
31
32 response = await browser.runtime.sendMessage(request);
33 } catch (error) {
34 response = { error };
35 }
36
37 // return response
38 window.postMessage(
39 { id: message.data.id, ext: 'smesh-signer', response },
40 message.origin
41 );
42 });
43
44 // Relay MLS push messages from background → page.
45 // The extension background pushes events (publish, DM, subscribe, status)
46 // when the marmot WASM produces output asynchronously.
47 browser.runtime.onMessage.addListener((message: any) => {
48 if (message?.ext === 'smesh-signer' && message?.type === 'mls-push') {
49 window.postMessage(message, '*');
50 }
51 });
52