-
Notifications
You must be signed in to change notification settings - Fork 0
/
PrintingPress.js
99 lines (91 loc) · 2.93 KB
/
PrintingPress.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
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
var PrintingPress = {
// all : connected (from content-scripts) ports separated by the events they're subscribed to
connections: {},
// backgroundChannels : all the channels the background script is subcribed to along with each channel's respective listeners
backgroundChannels: {},
// print : dispatcher
print: function() {
chrome.runtime.onConnect.addListener(function(port){
port.onMessage.addListener(function(msg){
if (msg.opts && msg.opts.background) {
if (PrintingPress.backgroundChannels[msg.publishTo]) {
for (var i = 0; i < PrintingPress.backgroundChannels[msg.publishTo].length; i += 1) {
if (msg.args) {
PrintingPress.backgroundChannels[msg.publishTo][i](msg.args);
}
else {
PrintingPress.backgroundChannels[msg.publishTo][i]();
}
}
}
}
else if (msg.subscribeTo) {
console.log("(PrintingPress.js) client subscribed to " + msg.subscribeTo + ".");;
if (PrintingPress.connections[msg.subscribeTo]) {
PrintingPress.connections[msg.subscribeTo].push(port);
}
else {
PrintingPress.connections[msg.subscribeTo] = [port];
}
}
else if (msg.publishTo) {
console.log("(PrintingPress.js) publishing message to " + msg.publishTo);
var
subscribers = PrintingPress.connections[msg.publishTo],
subscriber;
for (var i = 0; i < subscribers.length; i += 1) {
(function(subscriber){
if (!subscriber) {
return;
}
var response = {
'channel': msg.publishTo,
'args': msg.args
}
subscriber.postMessage(response);
})(subscribers[i]);
}
}
});
});
},
// on : background script listener
on: function(channel, func) {
if (PrintingPress.backgroundChannels[channel]) {
PrintingPress.backgroundChannels[channel].push(func)
}
else {
PrintingPress.backgroundChannels[channel] = [func];
}
},
// unsubscribeAll : unsubscribes all listeners
unsubscribeAll: function() {
this.connections = {};
this.backgroundChannels = {};
},
unsubscribe: function(opts) {
if (!opts)
return;
if (opts.tabChannels)
this.connections = {};
if (opts.backgroundChannels)
this.backgroundChannels = {};
},
publish: function(channel, args, opts) {
var
subscribers = this.connections[channel],
subscriber;
for (var i = 0; i < subscribers.length; i += 1) {
(function(subscriber, channel, args){
if ( !subscriber ) {
return;
}
var response = {
'channel' : channel,
'args': args
}
subscriber.postMessage(response);
})(subscribers[i], channel, args);
}
}
}