-
Notifications
You must be signed in to change notification settings - Fork 0
/
background.js
77 lines (73 loc) · 2.05 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
73
74
75
76
77
let contentScriptPorts = new Map();
chrome.runtime.onConnect.addListener((port) => {
if(port.name === CONTENT_SCRIPT) {
let tabId = port.sender.tab.id;
contentScriptPorts.set(tabId, new TabManager(port, tabId));
port.onDisconnect.addListener(() => {
contentScriptPorts.delete(tabId);
});
} else {
chrome.tabs.query({
active: true,
currentWindow: true,
}, (tabs) => {
let tabId = tabs[0].id;
let contentScriptPort = contentScriptPorts.get(tabId);
if(contentScriptPort) {
contentScriptPort.addPopupPort(port);
}
});
}
});
class TabManager {
constructor(port, tabId) {
this.contentScriptPort = port;
this.tabId = tabId;
this.popupPorts = new Set();
this.contentScriptPort.onDisconnect.addListener(() => {
this.hidePageAction();
});
this.contentScriptPort.onMessage.addListener((message) => {
if(message[TYPE] === INITIALIZE) {
this.initialMessage = message;
if(message[PLAYLISTS].length > 0) {
this.showPageAction();
} else {
this.hidePageAction();
}
} else if(message[TYPE] === NOTIFY) {
if(this.notificationText !== message[PLAYING]) {
this.notificationText = message[PLAYING];
chrome.notifications.create({
type: 'basic',
title: 'Now playing',
message: message[PLAYING] + '\n' + message[VIDEO],
iconUrl: 'icon48.png'
});
}
} else {
for(let port of this.popupPorts) {
port.postMessage(message);
}
}
});
}
addPopupPort(port) {
this.popupPorts.add(port);
port.postMessage(this.initialMessage);
port.onDisconnect.addListener(() => {
this.popupPorts.delete(port);
});
port.onMessage.addListener((message) => {
if(message[TYPE] === SEEK) {
this.contentScriptPort.postMessage(message);
}
});
}
showPageAction() {
chrome.pageAction.show(this.tabId);
}
hidePageAction() {
chrome.pageAction.hide(this.tabId);
}
}