UNPKG

2.12 kBJavaScriptView Raw
1/* @flow */
2/*global chrome:false*/
3'use strict';
4
5export type ChromeMessage = {
6 type: string;
7 body?: ?any; // should be Object | string; but in flow, Array is not Object
8};
9
10export 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
22export 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 // extension sending to itself
47 // (only for including trezor.js in the management part of the extension)
48 chrome.runtime.sendMessage(message, {}, callback);
49 } else {
50 // either another extension, or not sent from extension at all
51 // (this will be run most probably)
52 chrome.runtime.sendMessage(extensionId, message, {}, callback);
53 }
54 });
55}