summaryrefslogtreecommitdiff
path: root/src/lib
diff options
context:
space:
mode:
Diffstat (limited to 'src/lib')
-rw-r--r--src/lib/Messages.js31
1 files changed, 31 insertions, 0 deletions
diff --git a/src/lib/Messages.js b/src/lib/Messages.js
new file mode 100644
index 0000000..c87a8a8
--- /dev/null
+++ b/src/lib/Messages.js
@@ -0,0 +1,31 @@
+"use strict";
+{
+ let handlers = new Set();
+
+ let dispatch = async (msg, sender) => {
+ let {action} = msg;
+ for (let h of handlers) {
+ let f = h[action];
+ if (typeof f === "function") {
+ return await f(msg, sender);
+ }
+ }
+ };
+
+ var Messages = {
+ addHandler(handler) {
+ let originalSize = handlers.size;
+ handlers.add(handler);
+ if (originalSize === 0 && handlers.size === 1) {
+ browser.runtime.onMessage.addListener(dispatch);
+ }
+ },
+ removeHandler(handler) {
+ let originalSize = handlers.size;
+ handlers.delete(handler);
+ if (originalSize === 1 && handlers.size === 0) {
+ browser.runtime.onMessage.remveListener(dispatch);
+ }
+ }
+ }
+}