-
Notifications
You must be signed in to change notification settings - Fork 3
/
Copy pathcontentScript.ts
55 lines (49 loc) · 1.41 KB
/
contentScript.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
import { runtime } from 'webextension-polyfill';
import { PiralDebugApiMessage, PiralInspectorMessage } from './types';
/**
* window is marked as @deprecated in v3 but is still the official way to access external applications
* https://developer.chrome.com/docs/extensions/develop/concepts/content-scripts?hl=en#host-page-communication
*/
const handleMessage = (message: PiralDebugApiMessage) => {
if (typeof message === 'object' && message?.source === 'piral-debug-api') {
const { content } = message;
runtime.sendMessage(content);
if (content.type === 'available') {
console.info(`Piral Inspector (${content.kind}) connected!`);
}
}
};
/**
* Disconnects the Piral Inspector.
*/
window.addEventListener('unload', () => {
runtime.sendMessage({
type: 'unavailable',
});
});
/**
* Receives messages from the piral-debug-utils.js and forwards it to service worker
*/
window.addEventListener('message', (event) => {
if (event.source === window) {
const message: PiralDebugApiMessage = event.data;
handleMessage(message);
}
});
/**
* Receives messages from the service worker.js
*/
runtime.onMessage.addListener((content) => {
const message: PiralInspectorMessage = {
content,
source: 'piral-inspector',
version: 'v1',
};
window.postMessage(message, '*');
});
/**
* Tries to connect the instance to the dev tools.
*/
runtime.sendMessage({
type: 'cs-connect',
});