| 1 | /** |
| 2 | * This script is injected into the webpage being monitored |
| 3 | * |
| 4 | * @see https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Content_scripts |
| 5 | * @see https://developer.mozilla.org/en-US/docs/Mozilla/Add-ons/WebExtensions/Background_scripts |
| 6 | */ |
| 7 | |
| 8 | import { SOURCE_METRICS, SOURCE_CLIENT } from '@ipshipyard/libp2p-inspector-metrics' |
| 9 | import { SOURCE_SERVICE_WORKER } from './constants.js' |
| 10 | import { getBrowserInstance } from './utils/get-browser.js' |
| 11 | import type { DevToolsMessage } from './app.tsx' |
| 12 | |
| 13 | const browser = getBrowserInstance() |
| 14 | |
| 15 | let port: chrome.runtime.Port | undefined |
| 16 | |
| 17 | /** |
| 18 | * Receive events broadcast by `@ipshipyard/libp2p-inspector-metrics` and forward them on to |
| 19 | * the service worker, which forwards them on to the dev tools panel |
| 20 | */ |
| 21 | window.addEventListener('message', (event) => { |
| 22 | // Only accept messages from same frame |
| 23 | if (event.source !== window) { |
| 24 | return |
| 25 | } |
| 26 | |
| 27 | const message = event.data |
| 28 | |
| 29 | if (message?.source !== SOURCE_METRICS) { |
| 30 | // ignore messages from other sources |
| 31 | return |
| 32 | } |
| 33 | |
| 34 | // send message to worker |
| 35 | port?.postMessage(message) |
| 36 | }) |
| 37 | |
| 38 | /** |
| 39 | * Receive events broadcast by the service worker and forward them on to |
| 40 | * `@ipshipyard/libp2p-inspector-metrics`. |
| 41 | */ |
| 42 | browser.runtime.onConnect.addListener((p) => { |
| 43 | // only accept incoming connections from the service worker |
| 44 | if (p.name !== SOURCE_SERVICE_WORKER) { |
| 45 | return |
| 46 | } |
| 47 | |
| 48 | port = p |
| 49 | port.onMessage.addListener((message: DevToolsMessage) => { |
| 50 | if (message.source === SOURCE_CLIENT) { |
| 51 | // intercept copy-to-clipboard |
| 52 | if (message.type === 'copy-to-clipboard') { |
| 53 | navigator.clipboard.writeText(message.value) |
| 54 | .catch(err => { |
| 55 | // eslint-disable-next-line no-console |
| 56 | console.error('could not write to clipboard', err) |
| 57 | }) |
| 58 | |
| 59 | return |
| 60 | } |
| 61 | |
| 62 | window.postMessage(message, '*') |
| 63 | } |
| 64 | }) |
| 65 | |
| 66 | port.onDisconnect.addListener(() => { |
| 67 | port = undefined |
| 68 | }) |
| 69 | }) |