Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(503)

Side by Side Diff: chrome/renderer/resources/extensions/miscellaneous_bindings.js

Issue 15855010: Make ExtensionMsg_MessageInvoke run a module system function rather than a (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src
Patch Set: fix test compile Created 7 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
OLDNEW
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved. 1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be 2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file. 3 // found in the LICENSE file.
4 4
5 // This contains unprivileged javascript APIs for extensions and apps. It 5 // This contains unprivileged javascript APIs for extensions and apps. It
6 // can be loaded by any extension-related context, such as content scripts or 6 // can be loaded by any extension-related context, such as content scripts or
7 // background pages. See user_script_slave.cc for script that is loaded by 7 // background pages. See user_script_slave.cc for script that is loaded by
8 // content scripts only. 8 // content scripts only.
9 9
10 require('json_schema'); 10 var chrome = requireNative('chrome').GetChrome();
11 require('event_bindings');
11 var lastError = require('lastError'); 12 var lastError = require('lastError');
13 var logActivity = requireNative('activityLogger');
12 var miscNatives = requireNative('miscellaneous_bindings'); 14 var miscNatives = requireNative('miscellaneous_bindings');
13 var chrome = requireNative('chrome').GetChrome(); 15 var unloadEvent = require('unload_event');
14 var CloseChannel = miscNatives.CloseChannel; 16 var processNatives = requireNative('process');
15 var PortAddRef = miscNatives.PortAddRef;
16 var PortRelease = miscNatives.PortRelease;
17 var PostMessage = miscNatives.PostMessage;
18 var BindToGC = miscNatives.BindToGC;
19 17
20 var chromeHidden = requireNative('chrome_hidden').GetChromeHidden(); 18 // The reserved channel name for the sendRequest/send(Native)Message APIs.
21
22 var processNatives = requireNative('process');
23 var manifestVersion = processNatives.GetManifestVersion();
24 var extensionId = processNatives.GetExtensionId();
25
26 var logActivity = requireNative('activityLogger');
27
28 // The reserved channel name for the sendRequest/sendMessage APIs.
29 // Note: sendRequest is deprecated. 19 // Note: sendRequest is deprecated.
30 chromeHidden.kRequestChannel = "chrome.extension.sendRequest"; 20 var kRequestChannel = "chrome.extension.sendRequest";
31 chromeHidden.kMessageChannel = "chrome.runtime.sendMessage"; 21 var kMessageChannel = "chrome.runtime.sendMessage";
32 chromeHidden.kNativeMessageChannel = "chrome.runtime.sendNativeMessage"; 22 var kNativeMessageChannel = "chrome.runtime.sendNativeMessage";
33 23
34 // Map of port IDs to port object. 24 // Map of port IDs to port object.
35 var ports = {}; 25 var ports = {};
36 26
37 // Map of port IDs to chromeHidden.onUnload listeners. Keep track of these 27 // Map of port IDs to unloadEvent listeners. Keep track of these to free the
38 // to free the onUnload listeners when ports are closed. 28 // unloadEvent listeners when ports are closed.
39 var portReleasers = {}; 29 var portReleasers = {};
40 30
41 // Change even to odd and vice versa, to get the other side of a given 31 // Change even to odd and vice versa, to get the other side of a given
42 // channel. 32 // channel.
43 function getOppositePortId(portId) { return portId ^ 1; } 33 function getOppositePortId(portId) { return portId ^ 1; }
44 34
45 // Port object. Represents a connection to another script context through 35 // Port object. Represents a connection to another script context through
46 // which messages can be passed. 36 // which messages can be passed.
47 function PortImpl(portId, opt_name) { 37 function Port(portId, opt_name) {
48 this.portId_ = portId; 38 this.portId_ = portId;
49 this.name = opt_name; 39 this.name = opt_name;
50 this.onDisconnect = new chrome.Event(); 40 this.onDisconnect = new chrome.Event();
51 this.onMessage = new chrome.Event(); 41 this.onMessage = new chrome.Event();
52 } 42 }
53 43
54 // Sends a message asynchronously to the context on the other end of this 44 // Sends a message asynchronously to the context on the other end of this
55 // port. 45 // port.
56 PortImpl.prototype.postMessage = function(msg) { 46 Port.prototype.postMessage = function(msg) {
57 PostMessage(this.portId_, msg); 47 miscNatives.PostMessage(this.portId_, msg);
58 }; 48 };
59 49
60 // Disconnects the port from the other end. 50 // Disconnects the port from the other end.
61 PortImpl.prototype.disconnect = function() { 51 Port.prototype.disconnect = function() {
62 CloseChannel(this.portId_, true); 52 miscNatives.CloseChannel(this.portId_, true);
63 this.destroy_(); 53 this.destroy_();
64 }; 54 };
65 55
66 PortImpl.prototype.destroy_ = function() { 56 Port.prototype.destroy_ = function() {
67 var portId = this.portId_; 57 var portId = this.portId_;
68 58
69 this.onDisconnect.destroy_(); 59 this.onDisconnect.destroy_();
70 this.onMessage.destroy_(); 60 this.onMessage.destroy_();
71 61
72 PortRelease(portId); 62 miscNatives.PortRelease(portId);
73 chromeHidden.onUnload.removeListener(portReleasers[portId]); 63 unloadEvent.removeListener(portReleasers[portId]);
74 64
75 delete ports[portId]; 65 delete ports[portId];
76 delete portReleasers[portId]; 66 delete portReleasers[portId];
77 }; 67 };
78 68
79 chromeHidden.Port = {};
80
81 // Returns true if the specified port id is in this context. This is used by 69 // Returns true if the specified port id is in this context. This is used by
82 // the C++ to avoid creating the javascript message for all the contexts that 70 // the C++ to avoid creating the javascript message for all the contexts that
83 // don't care about a particular message. 71 // don't care about a particular message.
84 chromeHidden.Port.hasPort = function(portId) { 72 function hasPort(portId) {
85 return portId in ports; 73 return portId in ports;
86 }; 74 };
87 75
88 // Hidden port creation function. We don't want to expose an API that lets 76 // Hidden port creation function. We don't want to expose an API that lets
89 // people add arbitrary port IDs to the port list. 77 // people add arbitrary port IDs to the port list.
90 chromeHidden.Port.createPort = function(portId, opt_name) { 78 function createPort(portId, opt_name) {
91 if (ports[portId]) { 79 if (ports[portId])
92 throw new Error("Port '" + portId + "' already exists."); 80 throw new Error("Port '" + portId + "' already exists.");
93 } 81 var port = new Port(portId, opt_name);
94 var port = new PortImpl(portId, opt_name);
95 ports[portId] = port; 82 ports[portId] = port;
96 portReleasers[portId] = PortRelease.bind(this, portId); 83 portReleasers[portId] = miscNatives.PortRelease.bind(this, portId);
97 chromeHidden.onUnload.addListener(portReleasers[portId]); 84 unloadEvent.addListener(portReleasers[portId]);
98 85 miscNatives.PortAddRef(portId);
99 PortAddRef(portId);
100 return port; 86 return port;
101 }; 87 };
102 88
103 // Helper function for dispatchOnRequest. 89 // Helper function for dispatchOnRequest.
104 function handleSendRequestError(isSendMessage, 90 function handleSendRequestError(isSendMessage,
105 responseCallbackPreserved, 91 responseCallbackPreserved,
106 sourceExtensionId, 92 sourceExtensionId,
107 targetExtensionId, 93 targetExtensionId,
108 sourceUrl) { 94 sourceUrl) {
109 var errorMsg = []; 95 var errorMsg = [];
(...skipping 12 matching lines...) Expand all
122 errorMsg.push("for extension " + targetExtensionId); 108 errorMsg.push("for extension " + targetExtensionId);
123 if (sourceUrl != "") 109 if (sourceUrl != "")
124 errorMsg.push("for URL " + sourceUrl); 110 errorMsg.push("for URL " + sourceUrl);
125 lastError.set(eventName, errorMsg.join(" ") + ").", null, chrome); 111 lastError.set(eventName, errorMsg.join(" ") + ").", null, chrome);
126 } 112 }
127 113
128 // Helper function for dispatchOnConnect 114 // Helper function for dispatchOnConnect
129 function dispatchOnRequest(portId, channelName, sender, 115 function dispatchOnRequest(portId, channelName, sender,
130 sourceExtensionId, targetExtensionId, sourceUrl, 116 sourceExtensionId, targetExtensionId, sourceUrl,
131 isExternal) { 117 isExternal) {
132 var isSendMessage = channelName == chromeHidden.kMessageChannel; 118 var isSendMessage = channelName == kMessageChannel;
133 var requestEvent = (isSendMessage ? 119 var requestEvent = (isSendMessage ?
134 (isExternal ? 120 (isExternal ?
135 chrome.runtime.onMessageExternal : chrome.runtime.onMessage) : 121 chrome.runtime.onMessageExternal : chrome.runtime.onMessage) :
136 (isExternal ? 122 (isExternal ?
137 chrome.extension.onRequestExternal : chrome.extension.onRequest)); 123 chrome.extension.onRequestExternal : chrome.extension.onRequest));
138 if (requestEvent.hasListeners()) { 124 if (!requestEvent.hasListeners())
139 var port = chromeHidden.Port.createPort(portId, channelName); 125 return false;
140 port.onMessage.addListener(function(request) { 126 var port = createPort(portId, channelName);
141 var responseCallbackPreserved = false; 127 port.onMessage.addListener(function(request) {
142 var responseCallback = function(response) { 128 var responseCallbackPreserved = false;
143 if (port) { 129 var responseCallback = function(response) {
144 port.postMessage(response); 130 if (port) {
145 port.destroy_(); 131 port.postMessage(response);
146 port = null; 132 port.destroy_();
147 } else { 133 port = null;
148 // We nulled out port when sending the response, and now the page
149 // is trying to send another response for the same request.
150 handleSendRequestError(isSendMessage, responseCallbackPreserved,
151 sourceExtensionId, targetExtensionId);
152 }
153 };
154 // In case the extension never invokes the responseCallback, and also
155 // doesn't keep a reference to it, we need to clean up the port. Do
156 // so by attaching to the garbage collection of the responseCallback
157 // using some native hackery.
158 BindToGC(responseCallback, function() {
159 if (port) {
160 port.destroy_();
161 port = null;
162 }
163 });
164 if (!isSendMessage) {
165 requestEvent.dispatch(request, sender, responseCallback);
166 } else { 134 } else {
167 var rv = requestEvent.dispatch(request, sender, responseCallback); 135 // We nulled out port when sending the response, and now the page
168 responseCallbackPreserved = 136 // is trying to send another response for the same request.
169 rv && rv.results && rv.results.indexOf(true) > -1; 137 handleSendRequestError(isSendMessage, responseCallbackPreserved,
170 if (!responseCallbackPreserved && port) { 138 sourceExtensionId, targetExtensionId);
171 // If they didn't access the response callback, they're not 139 }
172 // going to send a response, so clean up the port immediately. 140 };
173 port.destroy_(); 141 // In case the extension never invokes the responseCallback, and also
174 port = null; 142 // doesn't keep a reference to it, we need to clean up the port. Do
175 } 143 // so by attaching to the garbage collection of the responseCallback
144 // using some native hackery.
145 miscNatives.BindToGC(responseCallback, function() {
146 if (port) {
147 port.destroy_();
148 port = null;
176 } 149 }
177 }); 150 });
178 var eventName = (isSendMessage ? 151 if (!isSendMessage) {
179 (isExternal ? 152 requestEvent.dispatch(request, sender, responseCallback);
180 "runtime.onMessageExternal" : "runtime.onMessage") : 153 } else {
181 (isExternal ? 154 var rv = requestEvent.dispatch(request, sender, responseCallback);
182 "extension.onRequestExternal" : "extension.onRequest")); 155 responseCallbackPreserved =
183 logActivity.LogEvent(targetExtensionId, 156 rv && rv.results && rv.results.indexOf(true) > -1;
184 eventName, 157 if (!responseCallbackPreserved && port) {
185 [sourceExtensionId, sourceUrl]); 158 // If they didn't access the response callback, they're not
186 return true; 159 // going to send a response, so clean up the port immediately.
187 } 160 port.destroy_();
188 return false; 161 port = null;
162 }
163 }
164 });
165 var eventName = (isSendMessage ?
166 (isExternal ?
167 "runtime.onMessageExternal" : "runtime.onMessage") :
168 (isExternal ?
169 "extension.onRequestExternal" : "extension.onRequest"));
170 logActivity.LogEvent(targetExtensionId,
171 eventName,
172 [sourceExtensionId, sourceUrl]);
173 return true;
189 } 174 }
190 175
191 // Called by native code when a channel has been opened to this context. 176 // Called by native code when a channel has been opened to this context.
192 chromeHidden.Port.dispatchOnConnect = function(portId, 177 function dispatchOnConnect(portId,
193 channelName, 178 channelName,
194 sourceTab, 179 sourceTab,
195 sourceExtensionId, 180 sourceExtensionId,
196 targetExtensionId, 181 targetExtensionId,
197 sourceUrl) { 182 sourceUrl) {
198 // Only create a new Port if someone is actually listening for a connection. 183 // Only create a new Port if someone is actually listening for a connection.
199 // In addition to being an optimization, this also fixes a bug where if 2 184 // In addition to being an optimization, this also fixes a bug where if 2
200 // channels were opened to and from the same process, closing one would 185 // channels were opened to and from the same process, closing one would
201 // close both. 186 // close both.
187 var extensionId = processNatives.GetExtensionId();
202 if (targetExtensionId != extensionId) 188 if (targetExtensionId != extensionId)
203 return false; // not for us 189 return false; // not for us
190
204 if (ports[getOppositePortId(portId)]) 191 if (ports[getOppositePortId(portId)])
205 return false; // this channel was opened by us, so ignore it 192 return false; // this channel was opened by us, so ignore it
206 193
207 // Determine whether this is coming from another extension, so we can use 194 // Determine whether this is coming from another extension, so we can use
208 // the right event. 195 // the right event.
209 var isExternal = sourceExtensionId != extensionId; 196 var isExternal = sourceExtensionId != extensionId;
210 197
211 var sender = {id: sourceExtensionId}; 198 var sender = {id: sourceExtensionId};
212 if (sourceUrl) 199 if (sourceUrl)
213 sender.url = sourceUrl; 200 sender.url = sourceUrl;
214 if (sourceTab) 201 if (sourceTab)
215 sender.tab = sourceTab; 202 sender.tab = sourceTab;
216 203
217 // Special case for sendRequest/onRequest and sendMessage/onMessage. 204 // Special case for sendRequest/onRequest and sendMessage/onMessage.
218 if (channelName == chromeHidden.kRequestChannel || 205 if (channelName == kRequestChannel || channelName == kMessageChannel) {
219 channelName == chromeHidden.kMessageChannel) {
220 return dispatchOnRequest(portId, channelName, sender, 206 return dispatchOnRequest(portId, channelName, sender,
221 sourceExtensionId, targetExtensionId, sourceUrl, 207 sourceExtensionId, targetExtensionId, sourceUrl,
222 isExternal); 208 isExternal);
223 } 209 }
224 210
225 var connectEvent = (isExternal ? 211 var connectEvent = (isExternal ?
226 chrome.runtime.onConnectExternal : chrome.runtime.onConnect); 212 chrome.runtime.onConnectExternal : chrome.runtime.onConnect);
227 if (connectEvent.hasListeners()) { 213 if (!connectEvent)
228 var port = chromeHidden.Port.createPort(portId, channelName); 214 return false;
229 port.sender = sender; 215 if (!connectEvent.hasListeners())
230 if (manifestVersion < 2) 216 return false;
231 port.tab = port.sender.tab;
232 217
233 var eventName = (isExternal ? 218 var port = createPort(portId, channelName);
234 "runtime.onConnectExternal" : "runtime.onConnect"); 219 port.sender = sender;
235 connectEvent.dispatch(port); 220 if (processNatives.manifestVersion < 2)
236 logActivity.LogEvent(targetExtensionId, 221 port.tab = port.sender.tab;
237 eventName, 222
238 [sourceExtensionId]); 223 var eventName = (isExternal ?
239 return true; 224 "runtime.onConnectExternal" : "runtime.onConnect");
240 } 225 connectEvent.dispatch(port);
241 return false; 226 logActivity.LogEvent(targetExtensionId,
227 eventName,
228 [sourceExtensionId]);
229 return true;
242 }; 230 };
243 231
244 // Called by native code when a channel has been closed. 232 // Called by native code when a channel has been closed.
245 chromeHidden.Port.dispatchOnDisconnect = function( 233 function dispatchOnDisconnect(portId, errorMessage) {
246 portId, errorMessage) {
247 var port = ports[portId]; 234 var port = ports[portId];
248 if (port) { 235 if (port) {
249 // Update the renderer's port bookkeeping, without notifying the browser. 236 // Update the renderer's port bookkeeping, without notifying the browser.
250 CloseChannel(portId, false); 237 miscNatives.CloseChannel(portId, false);
251 if (errorMessage) 238 if (errorMessage)
252 lastError.set('Port', errorMessage, null, chrome); 239 lastError.set('Port', errorMessage, null, chrome);
253 try { 240 try {
254 port.onDisconnect.dispatch(port); 241 port.onDisconnect.dispatch(port);
255 } finally { 242 } finally {
256 port.destroy_(); 243 port.destroy_();
257 lastError.clear(chrome); 244 lastError.clear(chrome);
258 } 245 }
259 } 246 }
260 }; 247 };
261 248
262 // Called by native code when a message has been sent to the given port. 249 // Called by native code when a message has been sent to the given port.
263 chromeHidden.Port.dispatchOnMessage = function(msg, portId) { 250 function dispatchOnMessage(msg, portId) {
264 var port = ports[portId]; 251 var port = ports[portId];
265 if (port) 252 if (port)
266 port.onMessage.dispatch(msg, port); 253 port.onMessage.dispatch(msg, port);
267 }; 254 };
268 255
269 // Shared implementation used by tabs.sendMessage and runtime.sendMessage. 256 // Shared implementation used by tabs.sendMessage and runtime.sendMessage.
270 chromeHidden.Port.sendMessageImpl = function(port, request, 257 function sendMessageImpl(port, request, responseCallback) {
271 responseCallback) { 258 if (port.name != kNativeMessageChannel)
272 if (port.name != chromeHidden.kNativeMessageChannel)
273 port.postMessage(request); 259 port.postMessage(request);
274 260
275 if (port.name == chromeHidden.kMessageChannel && !responseCallback) { 261 if (port.name == kMessageChannel && !responseCallback) {
276 // TODO(mpcomplete): Do this for the old sendRequest API too, after 262 // TODO(mpcomplete): Do this for the old sendRequest API too, after
277 // verifying it doesn't break anything. 263 // verifying it doesn't break anything.
278 // Go ahead and disconnect immediately if the sender is not expecting 264 // Go ahead and disconnect immediately if the sender is not expecting
279 // a response. 265 // a response.
280 port.disconnect(); 266 port.disconnect();
281 return; 267 return;
282 } 268 }
283 269
284 // Ensure the callback exists for the older sendRequest API. 270 // Ensure the callback exists for the older sendRequest API.
285 if (!responseCallback) 271 if (!responseCallback)
286 responseCallback = function() {}; 272 responseCallback = function() {};
287 273
288 port.onDisconnect.addListener(function() { 274 port.onDisconnect.addListener(function() {
289 // For onDisconnects, we only notify the callback if there was an error 275 // For onDisconnects, we only notify the callback if there was an error.
290 try { 276 try {
291 if (chrome.runtime.lastError) 277 if (chrome.runtime.lastError)
292 responseCallback(); 278 responseCallback();
293 } finally { 279 } finally {
294 port = null; 280 port = null;
295 } 281 }
296 }); 282 });
297 port.onMessage.addListener(function(response) { 283 port.onMessage.addListener(function(response) {
298 try { 284 try {
299 responseCallback(response); 285 responseCallback(response);
(...skipping 23 matching lines...) Expand all
323 // targetId (first argument, extensionId in the manfiest) is optional. 309 // targetId (first argument, extensionId in the manfiest) is optional.
324 var targetId = null; 310 var targetId = null;
325 if (lastArg >= 0) 311 if (lastArg >= 0)
326 targetId = args[lastArg--]; 312 targetId = args[lastArg--];
327 313
328 if (lastArg != -1) 314 if (lastArg != -1)
329 throw new Error('Invalid arguments to ' + functionName + '.'); 315 throw new Error('Invalid arguments to ' + functionName + '.');
330 return [targetId, request, responseCallback]; 316 return [targetId, request, responseCallback];
331 } 317 }
332 318
319 exports.kRequestChannel = kRequestChannel;
320 exports.kMessageChannel = kMessageChannel;
321 exports.kNativeMessageChannel = kNativeMessageChannel;
322 exports.Port = Port;
323 exports.createPort = createPort;
324 exports.sendMessageImpl = sendMessageImpl;
333 exports.sendMessageUpdateArguments = sendMessageUpdateArguments; 325 exports.sendMessageUpdateArguments = sendMessageUpdateArguments;
326
327 // For C++ code to call.
328 exports.hasPort = hasPort;
329 exports.dispatchOnConnect = dispatchOnConnect;
330 exports.dispatchOnDisconnect = dispatchOnDisconnect;
331 exports.dispatchOnMessage = dispatchOnMessage;
OLDNEW

Powered by Google App Engine
This is Rietveld 408576698