forked from darkreader/darkreader
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathchrome.ts
More file actions
60 lines (54 loc) · 2.07 KB
/
Copy pathchrome.ts
File metadata and controls
60 lines (54 loc) · 2.07 KB
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
import {MessageTypeCStoBG, MessageTypeBGtoCS} from '../utils/message';
import type {MessageBGtoCS} from '../definitions';
import {readResponseAsDataURL} from '../utils/network';
import {callFetchMethod} from './fetch';
if (!window.chrome) {
window.chrome = {} as any;
}
if (!chrome.runtime) {
chrome.runtime = {} as any;
}
const messageListeners = new Set<(message: MessageBGtoCS) => void>();
async function sendMessage(...args: any[]) {
if (args[0] && args[0].type === MessageTypeCStoBG.FETCH) {
const {id} = args[0];
try {
const {url, responseType} = args[0].data;
const response = await callFetchMethod(url);
let text: string;
if (responseType === 'data-url') {
text = await readResponseAsDataURL(response);
} else {
text = await response.text();
}
messageListeners.forEach((cb) => cb({type: MessageTypeBGtoCS.FETCH_RESPONSE, data: text, error: null, id}));
} catch (error) {
console.error(error);
messageListeners.forEach((cb) => cb({type: MessageTypeBGtoCS.FETCH_RESPONSE, data: null, error, id}));
}
}
}
function addMessageListener(callback: (data: any) => void) {
messageListeners.add(callback);
}
if (typeof chrome.runtime.sendMessage === 'function') {
const nativeSendMessage = chrome.runtime.sendMessage;
(chrome.runtime.sendMessage as unknown) = (...args: any[]) => {
sendMessage(...args);
nativeSendMessage.apply(chrome.runtime, args);
};
} else {
chrome.runtime.sendMessage = sendMessage;
}
if (!chrome.runtime.onMessage) {
chrome.runtime.onMessage = {} as any;
}
if (typeof chrome.runtime.onMessage.addListener === 'function') {
const nativeAddListener = chrome.runtime.onMessage.addListener;
chrome.runtime.onMessage.addListener = (...args: any[]) => {
addMessageListener(args[0]);
nativeAddListener.apply(chrome.runtime.onMessage, args);
};
} else {
chrome.runtime.onMessage.addListener = (...args: any[]) => addMessageListener(args[0]);
}