Rietveld Code Review Tool
Help | Bug tracker | Discussion group | Source code

Unified Diff: background.js

Issue 29370996: Issue 4783 - Use Port API for the messageResponder (Closed)
Patch Set: Add polyfilly for messaging API to background.js Created Jan. 13, 2017, 8 a.m.
Use n/p to move between diff chunks; N/P to move between comments.
Jump to:
View side-by-side diff with in-line comments
Download patch
« no previous file with comments | « no previous file | messageResponder.js » ('j') | messageResponder.js » ('J')
Expand Comments ('e') | Collapse Comments ('c') | Show Comments Hide Comments ('s')
Index: background.js
diff --git a/background.js b/background.js
index fa78123054da5bb29352923c3496ec8a049eecde..13fb5aa7f824db5ef3054ca23d443a38cfad3583 100644
--- a/background.js
+++ b/background.js
@@ -337,6 +337,74 @@
reinitialized: params.filterlistsReinitialized
};
+ let messageListeners = {};
+ modules.messaging = {
Sebastian Noack 2017/01/13 12:12:10 Can you please just use the EventEmitter class her
kzar 2017/01/16 04:27:02 Well I'm not sure I can since the EventEmitter cla
Sebastian Noack 2017/01/16 13:46:38 See line 20 in this file. There is a class called
kzar 2017/01/16 14:25:56 Oh yea, sorry I missed that. Done.
+ port: {
+ on: (name, callback) =>
+ {
+ if (!(name in messageListeners))
+ messageListeners[name] = [];
+ messageListeners[name].push(callback);
+ },
+ off: (name, callback) =>
+ {
+ if (!(name in messageListeners))
+ return;
+
+ let index = messageListeners[name].indexOf(callback);
+ if (index == -1)
+ return;
+
+ if (messageListeners[name].length == 1)
+ delete messageListeners[name];
+ else
+ messageListeners[name].splice(index, 1);
+ }
+ }
+ };
+ window.addEventListener("message", event =>
+ {
+ if (event.data.type != "message")
+ return;
+ let message = event.data.payload;
+ let messageId = event.data.messageId;
+ let sender = {
+ page: new ext.Page(event.source)
+ };
+
+ let listeners = messageListeners[message.type];
+ if (!listeners)
+ return;
+
+ function reply(message)
+ {
+ event.source.postMessage({
+ type: "response",
+ messageId: messageId,
+ payload: message
+ }, "*");
+ }
+
+ for (let listener of listeners)
+ {
+ let response = listener(message, sender);
+ if (response && typeof response.then == "function")
+ {
+ response.then(
+ reply,
+ reason => {
+ console.error(reason);
+ reply(undefined);
+ }
+ );
+ }
+ else if (typeof response != "undefined")
+ {
+ reply(response);
+ }
+ }
+ });
+
global.Services = {
vc: {
compare: function(v1, v2)
« no previous file with comments | « no previous file | messageResponder.js » ('j') | messageResponder.js » ('J')

Powered by Google App Engine
This is Rietveld