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
50 lines (43 loc) · 1.81 KB
/
runtime.ts
File metadata and controls
50 lines (43 loc) · 1.81 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
import { handleError } from "./common"
export function getRuntimeId(): string {
return chrome.runtime.id
}
export function sendMsg2Runtime<T = any, R = any>(code: timer.mq.ReqCode, data?: T): Promise<R> {
const request: timer.mq.Request<T> = { code, data }
return new Promise((resolve, reject) => chrome.runtime.sendMessage(request,
(response: timer.mq.Response<R>) => {
handleError('sendMsg2Runtime')
const resCode = response?.code
resCode === 'success'
? resolve(response.data)
: reject(new Error(response?.msg))
})
)
}
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>) => sendResponse(response))
// 'return ture' 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)
}