1 |
|
2 |
|
3 | 'use strict';
|
4 |
|
5 | export type ChromeMessage = {
|
6 | type: string;
|
7 | body?: ?any;
|
8 | };
|
9 |
|
10 | export async function exists(): Promise<void> {
|
11 | if (typeof chrome === `undefined`) {
|
12 | throw new Error(`Global chrome does not exist; probably not running chrome`);
|
13 | }
|
14 | if (typeof chrome.runtime === `undefined`) {
|
15 | throw new Error(`Global chrome.runtime does not exist; probably not running chrome`);
|
16 | }
|
17 | if (typeof chrome.runtime.sendMessage === `undefined`) {
|
18 | throw new Error(`Global chrome.runtime.sendMessage does not exist; probably not whitelisted website in extension manifest`);
|
19 | }
|
20 | }
|
21 |
|
22 | export function send(extensionId: string, message: ChromeMessage): Promise<mixed> {
|
23 | return new Promise(function (resolve, reject) {
|
24 | const callback = function (response?: mixed) {
|
25 | if (response === undefined) {
|
26 | console.error(`[trezor.js] [chrome-messages] Chrome runtime error`, chrome.runtime.lastError);
|
27 | reject(chrome.runtime.lastError);
|
28 | return;
|
29 | }
|
30 | if (typeof response !== `object` || response == null) {
|
31 | reject(new Error(`Response is not an object.`));
|
32 | return;
|
33 | }
|
34 | if (response.type === `response`) {
|
35 | resolve(response.body);
|
36 | } else if (response.type === `error`) {
|
37 | console.error(`[trezor.js] [chrome-messages] Error received`, response);
|
38 | reject(new Error(response.message));
|
39 | } else {
|
40 | console.error(`[trezor.js] [chrome-messages] Unknown response type `, JSON.stringify(response.type));
|
41 | reject(new Error(`Unknown response type ` + JSON.stringify(response.type)));
|
42 | }
|
43 | };
|
44 |
|
45 | if (chrome.runtime.id === extensionId) {
|
46 |
|
47 |
|
48 | chrome.runtime.sendMessage(message, {}, callback);
|
49 | } else {
|
50 |
|
51 |
|
52 | chrome.runtime.sendMessage(extensionId, message, {}, callback);
|
53 | }
|
54 | });
|
55 | }
|