summaryrefslogtreecommitdiffstats
path: root/browser/extensions/pocket/content/panels/js/messages.js
blob: ae08c3e73a3b2f8a08f433969f46c58c7a9f2f46 (plain)
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
// Documentation of methods used here are at:
// https://developer.mozilla.org/en-US/Add-ons/Code_snippets/Interaction_between_privileged_and_non-privileged_pages

var pktPanelMessaging = (function() {

 function panelIdFromURL(url) {
   var panelId = url.match(/panelId=([\w|\d|\.]*)&?/);
        if (panelId && panelId.length > 1) {
            return panelId[1];
        }

        return 0;
 }

 function prefixedMessageId(messageId) {
   return 'PKT_' + messageId;
 }

 function panelPrefixedMessageId(panelId, messageId) {
   return prefixedMessageId(panelId + '_' + messageId);
 }

 function addMessageListener(panelId, messageId, callback) {
   document.addEventListener(panelPrefixedMessageId(panelId, messageId), function(e) {

			callback(JSON.parse(e.target.getAttribute("payload"))[0]);

			// TODO: Figure out why e.target.parentNode is null
			// e.target.parentNode.removeChild(e.target);

		}, false);

	}

	function removeMessageListener(panelId, messageId, callback) {
   document.removeEventListener(panelPrefixedMessageId(panelId, messageId), callback);
	}

 function sendMessage(panelId, messageId, payload, callback) {
   // Payload needs to be an object in format:
   // { panelId: panelId, data: {} }
   var messagePayload = {
     panelId: panelId,
     data: (payload || {})
   };

		// Create a callback to listen for a response
		if (callback) {
	        var messageResponseId = messageId + "Response";
	        var responseListener = function(responsePayload) {
	            callback(responsePayload);
	            removeMessageListener(panelId, messageResponseId, responseListener);
	        }

	        addMessageListener(panelId, messageResponseId, responseListener);
	    }

	    // Send message
		var element = document.createElement("PKTMessageFromPanelElement");
		element.setAttribute("payload", JSON.stringify([messagePayload]));
		document.documentElement.appendChild(element);

		var evt = document.createEvent("Events");
		evt.initEvent(prefixedMessageId(messageId), true, false);
		element.dispatchEvent(evt);
	}


    /**
     * Public functions
     */
    return {
      panelIdFromURL: panelIdFromURL,
        addMessageListener : addMessageListener,
        removeMessageListener : removeMessageListener,
        sendMessage: sendMessage
    };
}());