forked from sheepzh/time-tracker-4-browser
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathruntime.ts
More file actions
69 lines (60 loc) · 2.46 KB
/
runtime.ts
File metadata and controls
69 lines (60 loc) · 2.46 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
61
62
63
64
65
66
67
68
69
import { handleError } from "./common"
export function getRuntimeId(): string {
return chrome.runtime.id
}
export function getRuntimeName(): string {
return chrome.runtime.getManifest().name
}
export function sendMsg2Runtime<T = any, R = any>(code: timer.mq.ReqCode, data?: T): Promise<R | undefined> {
// Fix proxy data failed to serialized in Firefox
if (data !== undefined) {
data = JSON.parse(JSON.stringify(data))
}
const request: timer.mq.Request<T> = { code, data }
return new Promise((resolve, reject) => {
try {
chrome.runtime.sendMessage(request, (response: timer.mq.Response<R>) => {
handleError('sendMsg2Runtime')
const resCode = response?.code
resCode === 'fail' && reject(new Error(response?.msg || 'Unknown error'))
resCode === 'success' && resolve(response.data)
})
} catch (e) {
reject('Failed to send message: ' + (e as Error)?.message || 'Unknown error')
}
})
}
export function onRuntimeMessage<T = any, R = any>(handler: ChromeMessageHandler<T, R>): void {
// Be careful!!!
// Can't use await/async in callback parameter
chrome.runtime.onMessage.addListener((message: timer.mq.Request<T>, sender: chrome.runtime.MessageSender, sendResponse: timer.mq.Callback<R>) => {
handler(message, sender).then((response: timer.mq.Response<R>) => {
if (response.code === 'ignore') return
sendResponse(response)
})
// 'return true' will force chrome to wait for the response processed in the above promise.
// @see https://github.com/mozilla/webextension-polyfill/issues/130
return true
})
}
export function onInstalled(handler: (reason: ChromeOnInstalledReason) => void): void {
chrome.runtime.onInstalled.addListener(detail => handler(detail.reason))
}
export function getVersion(): string {
return chrome.runtime.getManifest().version
}
export function setUninstallURL(url: string): Promise<void> {
return new Promise(resolve => chrome.runtime.setUninstallURL(url, resolve))
}
/**
* Get the url of this extension
*
* @param path The path relative to the root directory of this extension
*/
export function getUrl(path: string): string {
return chrome.runtime.getURL(path)
}
export async function isAllowedFileSchemeAccess(): Promise<boolean> {
const res = await chrome.extension?.isAllowedFileSchemeAccess?.()
return !!res
}