1 /* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */
7 const DevToolsUtils = require("devtools/shared/DevToolsUtils");
8 const { LongStringFront } = require("devtools/shared/fronts/string");
12 } = require("devtools/shared/protocol");
13 const { webconsoleSpec } = require("devtools/shared/specs/webconsole");
15 getAdHocFrontOrPrimitiveGrip,
16 } = require("devtools/shared/fronts/object");
19 * A WebConsoleFront is used as a front end for the WebConsoleActor that is
20 * created on the server, hiding implementation details.
22 * @param object client
23 * The DevToolsClient instance we live for.
25 class WebConsoleFront extends FrontClassWithSpec(webconsoleSpec) {
26 constructor(client, targetFront, parentFront) {
27 super(client, targetFront, parentFront);
28 this._client = client;
30 this._longStrings = {};
33 // Attribute name from which to retrieve the actorID out of the target actor's form
34 this.formAttributeName = "consoleActor";
36 * Holds the network requests currently displayed by the Web Console. Each key
37 * represents the connection ID and the value is network request information.
41 this._networkRequests = new Map();
43 this.pendingEvaluationResults = new Map();
44 this.onEvaluationResult = this.onEvaluationResult.bind(this);
45 this.onNetworkEvent = this._onNetworkEvent.bind(this);
46 this.onNetworkEventUpdate = this._onNetworkEventUpdate.bind(this);
48 this.on("evaluationResult", this.onEvaluationResult);
49 this.on("serverNetworkEvent", this.onNetworkEvent);
50 this.before("consoleAPICall", this.beforeConsoleAPICall);
51 this.before("pageError", this.beforePageError);
53 this._client.on("networkEventUpdate", this.onNetworkEventUpdate);
56 getNetworkRequest(actorId) {
57 return this._networkRequests.get(actorId);
61 return this._networkRequests.values();
69 * The "networkEvent" message type handler. We redirect any message to
70 * the UI for displaying.
75 * @param object packet
76 * The message received from the server.
78 _onNetworkEvent(packet) {
79 const actor = packet.eventActor;
81 _type: "NetworkEvent",
82 timeStamp: actor.timeStamp,
85 discardRequestBody: true,
86 discardResponseBody: true,
87 startedDateTime: actor.startedDateTime,
96 // track the list of network event updates
98 private: actor.private,
99 fromCache: actor.fromCache,
100 fromServiceWorker: actor.fromServiceWorker,
101 isThirdPartyTrackingResource: actor.isThirdPartyTrackingResource,
102 referrerPolicy: actor.referrerPolicy,
103 blockedReason: actor.blockedReason,
104 channelId: actor.channelId,
106 this._networkRequests.set(actor.actor, networkInfo);
108 this.emit("networkEvent", networkInfo);
112 * The "networkEventUpdate" message type handler. We redirect any message to
113 * the UI for displaying.
118 * @param object packet
119 * The message received from the server.
121 _onNetworkEventUpdate(packet) {
122 const networkInfo = this.getNetworkRequest(packet.from);
127 networkInfo.updates.push(packet.updateType);
129 switch (packet.updateType) {
130 case "requestHeaders":
131 networkInfo.request.headersSize = packet.headersSize;
133 case "requestPostData":
134 networkInfo.discardRequestBody = packet.discardRequestBody;
135 networkInfo.request.bodySize = packet.dataSize;
137 case "responseStart":
138 networkInfo.response.httpVersion = packet.response.httpVersion;
139 networkInfo.response.status = packet.response.status;
140 networkInfo.response.statusText = packet.response.statusText;
141 networkInfo.response.headersSize = packet.response.headersSize;
142 networkInfo.response.remoteAddress = packet.response.remoteAddress;
143 networkInfo.response.remotePort = packet.response.remotePort;
144 networkInfo.discardResponseBody = packet.response.discardResponseBody;
146 case "responseContent":
147 networkInfo.response.content = {
148 mimeType: packet.mimeType,
150 networkInfo.response.bodySize = packet.contentSize;
151 networkInfo.response.transferredSize = packet.transferredSize;
152 networkInfo.discardResponseBody = packet.discardResponseBody;
155 networkInfo.totalTime = packet.totalTime;
158 networkInfo.securityState = packet.state;
160 case "responseCache":
161 networkInfo.response.responseCache = packet.responseCache;
165 this.emit("networkEventUpdate", {
172 * Evaluate a JavaScript expression asynchronously.
174 * @param {String} string: The code you want to evaluate.
175 * @param {Object} opts: Options for evaluation:
177 * - {String} frameActor: a FrameActor ID. The FA holds a reference to
178 * a Debugger.Frame. This option allows you to evaluate the string in
179 * the frame of the given FA.
181 * - {String} url: the url to evaluate the script as. Defaults to
182 * "debugger eval code".
184 * - {String} selectedNodeActor: the NodeActor ID of the current
185 * selection in the Inspector, if such a selection
186 * exists. This is used by helper functions that can
187 * reference the currently selected node in the Inspector, like $0.
189 * - {String} selectedObjectActor: the actorID of a given objectActor.
190 * This is used by context menu entries to get a reference to an object, in order
191 * to perform some operation on it (copy it, store it as a global variable, …).
193 * @return {Promise}: A promise that resolves with the response.
195 async evaluateJSAsync(string, opts = {}) {
198 frameActor: opts.frameActor,
200 selectedNodeActor: opts.selectedNodeActor,
201 selectedObjectActor: opts.selectedObjectActor,
206 this._pendingAsyncEvaluation = super.evaluateJSAsync(options);
207 const { resultID } = await this._pendingAsyncEvaluation;
208 this._pendingAsyncEvaluation = null;
210 return new Promise((resolve, reject) => {
211 // Null check this in case the client has been detached while sending
212 // the one way request
213 if (this.pendingEvaluationResults) {
214 this.pendingEvaluationResults.set(resultID, resp => {
219 resp.result = getAdHocFrontOrPrimitiveGrip(resp.result, this);
222 if (resp.helperResult && resp.helperResult.object) {
223 resp.helperResult.object = getAdHocFrontOrPrimitiveGrip(
224 resp.helperResult.object,
229 if (resp.exception) {
230 resp.exception = getAdHocFrontOrPrimitiveGrip(
236 if (resp.exceptionMessage) {
237 resp.exceptionMessage = getAdHocFrontOrPrimitiveGrip(
238 resp.exceptionMessage,
251 * Handler for the actors's unsolicited evaluationResult packet.
253 async onEvaluationResult(packet) {
254 // In some cases, the evaluationResult event can be received before the initial call
255 // to evaluationJSAsync completes. So make sure to wait for the corresponding promise
256 // before handling the event.
257 await this._pendingAsyncEvaluation;
259 // Find the associated callback based on this ID, and fire it.
260 // In a sync evaluation, this would have already been called in
261 // direct response to the client.request function.
262 const onResponse = this.pendingEvaluationResults.get(packet.resultID);
265 this.pendingEvaluationResults.delete(packet.resultID);
267 DevToolsUtils.reportException(
268 "onEvaluationResult",
269 "No response handler for an evaluateJSAsync result (resultID: " +
276 beforeConsoleAPICall(packet) {
277 if (packet.message && Array.isArray(packet.message.arguments)) {
278 // We might need to create fronts for each of the message arguments.
279 packet.message.arguments = packet.message.arguments.map(arg =>
280 getAdHocFrontOrPrimitiveGrip(arg, this)
286 beforePageError(packet) {
287 if (packet && packet.pageError && packet.pageError.errorMessage) {
288 packet.pageError.errorMessage = getAdHocFrontOrPrimitiveGrip(
289 packet.pageError.errorMessage,
296 async getCachedMessages(messageTypes) {
297 const response = await super.getCachedMessages(messageTypes);
298 if (Array.isArray(response.messages)) {
299 response.messages = response.messages.map(message => {
300 if (!message || !Array.isArray(message.arguments)) {
304 // We might need to create fronts for each of the message arguments.
305 message.arguments = message.arguments.map(arg =>
306 getAdHocFrontOrPrimitiveGrip(arg, this)
315 * Retrieve the request headers from the given NetworkEventActor.
317 * @param string actor
318 * The NetworkEventActor ID.
319 * @param function onResponse
320 * The function invoked when the response is received.
322 * Request object that implements both Promise and EventEmitter interfaces
324 getRequestHeaders(actor, onResponse) {
327 type: "getRequestHeaders",
329 return this._client.request(packet, onResponse);
333 * Retrieve the request cookies from the given NetworkEventActor.
335 * @param string actor
336 * The NetworkEventActor ID.
337 * @param function onResponse
338 * The function invoked when the response is received.
340 * Request object that implements both Promise and EventEmitter interfaces
342 getRequestCookies(actor, onResponse) {
345 type: "getRequestCookies",
347 return this._client.request(packet, onResponse);
351 * Retrieve the request post data from the given NetworkEventActor.
353 * @param string actor
354 * The NetworkEventActor ID.
355 * @param function onResponse
356 * The function invoked when the response is received.
358 * Request object that implements both Promise and EventEmitter interfaces
360 getRequestPostData(actor, onResponse) {
363 type: "getRequestPostData",
365 return this._client.request(packet, onResponse);
369 * Retrieve the response headers from the given NetworkEventActor.
371 * @param string actor
372 * The NetworkEventActor ID.
373 * @param function onResponse
374 * The function invoked when the response is received.
376 * Request object that implements both Promise and EventEmitter interfaces
378 getResponseHeaders(actor, onResponse) {
381 type: "getResponseHeaders",
383 return this._client.request(packet, onResponse);
387 * Retrieve the response cookies from the given NetworkEventActor.
389 * @param string actor
390 * The NetworkEventActor ID.
391 * @param function onResponse
392 * The function invoked when the response is received.
394 * Request object that implements both Promise and EventEmitter interfaces
396 getResponseCookies(actor, onResponse) {
399 type: "getResponseCookies",
401 return this._client.request(packet, onResponse);
405 * Retrieve the response content from the given NetworkEventActor.
407 * @param string actor
408 * The NetworkEventActor ID.
409 * @param function onResponse
410 * The function invoked when the response is received.
412 * Request object that implements both Promise and EventEmitter interfaces
414 getResponseContent(actor, onResponse) {
417 type: "getResponseContent",
419 return this._client.request(packet, onResponse);
423 * Retrieve the response cache from the given NetworkEventActor
425 * @param string actor
426 * The NetworkEventActor ID.
427 * @param function onResponse
428 * The function invoked when the response is received.
430 * Request object that implements both Promise and EventEmitter interfaces.
432 getResponseCache(actor, onResponse) {
435 type: "getResponseCache",
437 return this._client.request(packet, onResponse);
441 * Retrieve the timing information for the given NetworkEventActor.
443 * @param string actor
444 * The NetworkEventActor ID.
445 * @param function onResponse
446 * The function invoked when the response is received.
448 * Request object that implements both Promise and EventEmitter interfaces
450 getEventTimings(actor, onResponse) {
453 type: "getEventTimings",
455 return this._client.request(packet, onResponse);
459 * Retrieve the security information for the given NetworkEventActor.
461 * @param string actor
462 * The NetworkEventActor ID.
463 * @param function onResponse
464 * The function invoked when the response is received.
466 * Request object that implements both Promise and EventEmitter interfaces
468 getSecurityInfo(actor, onResponse) {
471 type: "getSecurityInfo",
473 return this._client.request(packet, onResponse);
477 * Retrieve the stack-trace information for the given NetworkEventActor.
479 * @param string actor
480 * The NetworkEventActor ID.
481 * @param function onResponse
482 * The function invoked when the stack-trace is received.
484 * Request object that implements both Promise and EventEmitter interfaces
486 getStackTrace(actor, onResponse) {
489 type: "getStackTrace",
491 return this._client.request(packet, onResponse);
495 * Start the given Web Console listeners.
496 * TODO: remove once the front is retrieved via getFront, and we use form()
498 * @see this.LISTENERS
499 * @param array listeners
500 * Array of listeners you want to start. See this.LISTENERS for
503 * Request object that implements both Promise and EventEmitter interfaces
505 async startListeners(listeners) {
506 const response = await super.startListeners(listeners);
507 this.hasNativeConsoleAPI = response.nativeConsoleAPI;
508 this.traits = response.traits;
513 * Return an instance of LongStringFront for the given long string grip.
516 * The long string grip returned by the protocol.
517 * @return {LongStringFront} the front for the given long string grip.
520 if (grip.actor in this._longStrings) {
521 return this._longStrings[grip.actor];
524 const front = new LongStringFront(this._client, this.targetFront, this);
527 this._longStrings[grip.actor] = front;
532 * Fetches the full text of a LongString.
534 * @param object | string stringGrip
535 * The long string grip containing the corresponding actor.
536 * If you pass in a plain string (by accident or because you're lazy),
537 * then a promise of the same string is simply returned.
538 * @return object Promise
539 * A promise that is resolved when the full string contents
540 * are available, or rejected if something goes wrong.
542 async getString(stringGrip) {
543 // Make sure this is a long string.
544 if (typeof stringGrip !== "object" || stringGrip.type !== "longString") {
545 // Go home string, you're drunk.
549 // Fetch the long string only once.
550 if (stringGrip._fullText) {
551 return stringGrip._fullText;
554 const { initial, length } = stringGrip;
555 const longStringFront = this.longString(stringGrip);
558 const response = await longStringFront.substring(initial.length, length);
559 return initial + response;
561 DevToolsUtils.reportException("getString", e.message);
566 clearNetworkRequests() {
567 // Prevent exception if the front has already been destroyed.
568 if (this._networkRequests) {
569 this._networkRequests.clear();
574 * Close the WebConsoleFront.
582 this._client.off("networkEventUpdate", this.onNetworkEventUpdate);
583 // This will make future calls to this function harmless because of the early return
584 // at the top of the function.
587 this.off("evaluationResult", this.onEvaluationResult);
588 this.off("serverNetworkEvent", this.onNetworkEvent);
589 this._longStrings = null;
590 this.pendingEvaluationResults.clear();
591 this.pendingEvaluationResults = null;
592 this.clearNetworkRequests();
593 this._networkRequests = null;
594 return super.destroy();
598 exports.WebConsoleFront = WebConsoleFront;
599 registerFront(WebConsoleFront);