aboutsummaryrefslogtreecommitdiff
path: root/js/firefox/page-shim.js
blob: ec05f8fabcac6dd57957f866b01e8d7e26d92b01 (plain) (blame)
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
(function() {
	//Communication functions for

	if (typeof chrome !== 'undefined') {
		return;
	}

	function log(msg) {
		window.postMessage({sender:'page', logMessage: msg}, '*');	
	}

	var messageId = 1;
	var callbacks = {};
	function send(type, message, callback) {
		var id = messageId++;
		window.postMessage({sender:'page', url:location.href, messageId:id, messageType:type, payload:message}, '*');
		callbacks[id] = callback;
	}

	window.addEventListener('message', function(message) {
		if (message.data.sender == 'page') {
			return; //Ignore messages we sent ourselves
		}
		log('page got message: ' + JSON.stringify(message.data));
		
		var callback = callbacks[message.data.messageId];
		if (callback) {
			callback(message.data.payload);
			delete callbacks[message.data.messageId];
		}
	});

	//Allow Firefox users to turn on logging
	window.logging = {
		enable : function() {
			send('log.enabled', {enabled:true});
		},

		disable : function() {
			send('log.enabled', {enabled:false});
		}
	}

	var req = new XMLHttpRequest();
	req.overrideMimeType('application/json');
	req.open("GET", 'package.json', false);
	req.send();	
	var manifest = JSON.parse(req.responseText);

	window.chrome = {
		storage : {
			local : {
				get : function(query, callback) {
					send('storage.get', query, callback);
				},
				set : function(data, callback) {
					send('storage.set', data, callback);
				}
			}
		},

		extension : {
			getURL : function(file) {
				return document.location.protocol + '//' + document.location.host + '/' + file;
			}
		},

		tabs : {
			query : function(data, callback) {
				send('tabs.query', data, callback);
			},

			create : function(data, callback) {
				send('tabs.create', data, callback);
			},

			update : function(tabId, options, callback) {
				if (!options.active) {
					throw 'Unexpected update call';
				}

				options.tabId = tabId;

				send('tabs.update', options, callback);
			}
		},

		runtime : { 
			getManifest : function() {
				return manifest;
			}
		}
	};

})();