-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathpopup.js
71 lines (65 loc) · 1.5 KB
/
popup.js
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
/* globals chrome */
const dom = require('./dom');
const RESULT_TYPES = ['success', 'error'];
/*
* Manipulate the DOM to display a result.
*/
function showResult(type, payload) {
dom.hide('.initial, .toggle');
dom.setValue('#payload', payload);
dom.show(`.toggle.${type}`);
dom.select('#payload');
}
/*
* Add an extension messaging listener to receive messages from the injected
* content script and display the results.
*/
function addListener() {
return new Promise((resolve) => {
chrome.runtime.onMessage.addListener((message) => {
if (!message) {
return;
}
if (RESULT_TYPES.indexOf(message.type) === -1) {
showResult(
'error',
`Unexpected extension message type: ${message.type}`
);
return;
}
showResult(message.type, message.payload);
});
resolve();
});
}
/*
* Return the active tab.
*/
function getTab() {
return new Promise((resolve, reject) => {
chrome.tabs.query({
currentWindow: true,
active: true,
}, (tabs) => {
if (tabs.length !== 1) {
reject(`Unexpected active tab count: ${tabs.length}`);
} else {
resolve(tabs[0]);
}
});
});
}
/*
* Inject and execute the content script.
*/
function executeScript(tab) {
return new Promise((resolve) => {
chrome.tabs.executeScript(tab.tabId, {
file: 'lib/inject.js',
}, resolve);
});
}
addListener()
.then(getTab)
.then(executeScript)
.catch(showResult.bind(null, 'error'));