generated from chibat/chrome-extension-typescript-starter
-
Notifications
You must be signed in to change notification settings - Fork 1.8k
/
Copy pathindex.ts
99 lines (89 loc) · 2.47 KB
/
index.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
import browser from 'webextension-polyfill'
browser.contextMenus.create(
{
id: 'open-translator',
type: 'normal',
title: 'OpenAI Translator',
contexts: ['page', 'selection'],
},
() => {
browser.runtime.lastError
}
)
browser.contextMenus.onClicked.addListener(async function (info) {
const [tab] = await chrome.tabs.query({ active: true })
tab.id &&
browser.tabs.sendMessage(tab.id, {
type: 'open-translator',
info,
})
})
interface BackgroundFetchMessage {
type: 'open' | 'abort'
details: { url: string; options: RequestInit }
}
async function fetchWithStream(port: browser.Runtime.Port, message: BackgroundFetchMessage, signal: AbortSignal) {
const { url, options } = message.details
let response: Response | null = null
try {
response = await fetch(url, { ...options, signal })
} catch (error) {
if (error instanceof Error) {
const { message, name } = error
port.postMessage({
error: { message, name },
})
}
port.disconnect()
return
}
const responseSend = {
ok: response.ok,
status: response.status,
statusText: response.statusText,
redirected: response.redirected,
type: response.type,
url: response.url,
}
const reader = response?.body?.getReader()
if (!reader) {
port.postMessage(responseSend)
return
}
try {
// eslint-disable-next-line no-constant-condition
while (true) {
const { done, value } = await reader.read()
if (done) {
break
}
const str = new TextDecoder().decode(value)
port.postMessage({
...responseSend,
data: str,
})
}
} catch (error) {
console.log(error)
} finally {
port.disconnect()
reader.releaseLock()
}
}
browser.runtime.onConnect.addListener(async function (port) {
if (port.name !== 'background-fetch') {
return
}
const controller = new AbortController()
const { signal } = controller
port.onMessage.addListener(function (message) {
switch (message.type) {
case 'abort':
controller.abort()
break
case 'open':
fetchWithStream(port, message, signal)
break
}
})
})