-
Notifications
You must be signed in to change notification settings - Fork 0
/
content.js
67 lines (55 loc) · 1.36 KB
/
content.js
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
56
57
58
59
60
61
62
63
64
65
66
67
'use strict';
import browser from "webextension-polyfill";
let port = browser.runtime.connect();
function onPortMessage(msg, port) {
if (typeof msg.type !== 'string') {
return;
}
switch (msg.type) {
case 'bind':
removeListeners();
addListeners(msg.events);
break;
case 'unbind':
removeListeners();
break;
}
}
function onEvent(e) {
port.postMessage({
type: 'content.on',
event: {
type: e.type
}
});
}
function toggleListener(target, eventName, handler, toggle) {
if (toggle) {
target.addEventListener(eventName, handler);
} else {
target.removeEventListener(eventName, handler);
}
}
function addListeners(events) {
const types = Object.keys(events);
toggleListener(window, 'copy', onEvent, types.includes('window.copy'));
toggleListener(window, 'cut', onEvent, types.includes('window.cut'));
}
function removeListeners() {
window.removeEventListener('copy', onEvent);
window.removeEventListener('cut', onEvent);
}
globalThis.requestIdleCallback(() => {
port = browser.runtime.connect();
port.postMessage({type: 'ready'});
port.onMessage.addListener(onPortMessage);
port.onDisconnect.addListener((p) => { // stop when background script unload
port = null;
removeListeners();
});
window.addEventListener('unload', () => {
if (port) {
port.disconnect();
}
});
});