From 1de1db3c29d11f49e130d44db359d1187f6c24a0 Mon Sep 17 00:00:00 2001 From: hackademix Date: Tue, 21 Aug 2018 23:54:04 +0200 Subject: Fixed possible surprises in background script message handling. --- src/lib/Messages.js | 31 +++++++++++++++++++++++++++++++ 1 file changed, 31 insertions(+) create mode 100644 src/lib/Messages.js (limited to 'src/lib') 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); + } + } + } +} -- cgit v1.2.3