-
Notifications
You must be signed in to change notification settings - Fork 1
/
background.js
72 lines (68 loc) · 1.87 KB
/
background.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
72
const {
REQUEST_TYPE_SYNC_EMITFULL,
REQUEST_TYPE_SYNC_FULL,
REQUEST_TYPE_SYNC_TO_BG,
REQUEST_TYPE_SYNC_TO_TAB,
canSendAction,
handleSendMessageResponse,
markActionAsSynchronised
} = require("./shared.js");
function createSyncMiddleware() {
return () => next => action => {
if (canSendAction(action)) {
// mark as having been sync'd
markActionAsSynchronised(action);
// send the state update
sendStateUpdate(action);
}
// continue with the next middleware
next(action);
};
}
function sendStateUpdate(action) {
const fetchTabs = new Promise(resolve => chrome.tabs.query({}, tabs => resolve(tabs)));
return fetchTabs.then(tabs => {
tabs.forEach(tab => {
chrome.tabs.sendMessage(
tab.id,
{
type: REQUEST_TYPE_SYNC_TO_TAB,
action
},
undefined,
handleSendMessageResponse
);
});
// handle popup
chrome.runtime.sendMessage(
{
type: REQUEST_TYPE_SYNC_TO_TAB,
action
},
undefined,
handleSendMessageResponse
);
});
}
function syncStore(store) {
const { dispatch, getState } = store;
const handler = (request, sender, sendResponse) => {
if (!request) {
return;
}
if (request.type === REQUEST_TYPE_SYNC_TO_BG) {
dispatch(request.action);
} else if (request.type === REQUEST_TYPE_SYNC_EMITFULL) {
sendResponse({
type: REQUEST_TYPE_SYNC_FULL,
state: getState()
});
}
};
chrome.runtime.onMessage.addListener(handler);
return store;
}
module.exports = {
createSyncMiddleware,
syncStore
};