forked from darkreader/darkreader
-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathnetwork.ts
More file actions
52 lines (43 loc) · 1.72 KB
/
Copy pathnetwork.ts
File metadata and controls
52 lines (43 loc) · 1.72 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
import {isFirefox} from './platform';
async function getOKResponse(url: string, mimeType?: string, origin?: string): Promise<Response> {
const response = await fetch(
url,
{
cache: 'force-cache',
credentials: 'omit',
referrer: origin,
},
);
// Firefox bug, content type is "application/x-unknown-content-type"
if (isFirefox && mimeType === 'text/css' && url.startsWith('moz-extension://') && url.endsWith('.css')) {
return response;
}
if (mimeType && !response.headers.get('Content-Type')!.startsWith(mimeType)) {
throw new Error(`Mime type mismatch when loading ${url}`);
}
if (!response.ok) {
throw new Error(`Unable to load ${url} ${response.status} ${response.statusText}`);
}
return response;
}
export async function loadAsDataURL(url: string, mimeType?: string): Promise<string> {
const response = await getOKResponse(url, mimeType);
return await readResponseAsDataURL(response);
}
export async function loadAsBlob(url: string, mimeType?: string): Promise<Blob> {
const response = await getOKResponse(url, mimeType);
return await response.blob();
}
export async function readResponseAsDataURL(response: Response): Promise<string> {
const blob = await response.blob();
const dataURL = await (new Promise<string>((resolve) => {
const reader = new FileReader();
reader.onloadend = () => resolve(reader.result as string);
reader.readAsDataURL(blob);
}));
return dataURL;
}
export async function loadAsText(url: string, mimeType?: string, origin?: string): Promise<string> {
const response = await getOKResponse(url, mimeType, origin);
return await response.text();
}