summaryrefslogtreecommitdiffstats
path: root/devtools/shared/commands/resource/legacy-listeners/console-messages.js
blob: ae3f81b4df2a2e1012e070ae9962ac4151795aed (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
/* This Source Code Form is subject to the terms of the Mozilla Public
 * License, v. 2.0. If a copy of the MPL was not distributed with this
 * file, You can obtain one at http://mozilla.org/MPL/2.0/. */

"use strict";

const ResourceCommand = require("resource://devtools/shared/commands/resource/resource-command.js");

module.exports = async function ({ targetCommand, targetFront, onAvailable }) {
  // Allow the top level target unconditionnally.
  // Also allow frame, but only in content toolbox, i.e. still ignore them in
  // the context of the browser toolbox as we inspect messages via the process
  // targets
  const listenForFrames = targetCommand.descriptorFront.isTabDescriptor;

  // Allow workers when messages aren't dispatched to the main thread.
  const listenForWorkers =
    !targetCommand.rootFront.traits
      .workerConsoleApiMessagesDispatchedToMainThread;

  const acceptTarget =
    targetFront.isTopLevel ||
    targetFront.targetType === targetCommand.TYPES.PROCESS ||
    (targetFront.targetType === targetCommand.TYPES.FRAME && listenForFrames) ||
    (targetFront.targetType === targetCommand.TYPES.WORKER && listenForWorkers);

  if (!acceptTarget) {
    return;
  }

  const webConsoleFront = await targetFront.getFront("console");
  if (webConsoleFront.isDestroyed()) {
    return;
  }

  // Request notifying about new messages
  await webConsoleFront.startListeners(["ConsoleAPI"]);

  // Fetch already existing messages
  // /!\ The actor implementation requires to call startListeners(ConsoleAPI) first /!\
  const { messages } = await webConsoleFront.getCachedMessages(["ConsoleAPI"]);

  for (const message of messages) {
    message.resourceType = ResourceCommand.TYPES.CONSOLE_MESSAGE;
  }
  onAvailable(messages);

  // Forward new message events
  webConsoleFront.on("consoleAPICall", message => {
    // Ignore console messages that are cloned from the content process
    // (they aren't relevant to toolboxes still using legacy listeners)
    if (message.clonedFromContentProcess) {
      return;
    }

    message.resourceType = ResourceCommand.TYPES.CONSOLE_MESSAGE;
    onAvailable([message]);
  });
};