Skip to content

try-catch in event listeners #22

@avalanche1

Description

@avalanche1

Is try-catch error handling described here supposed to work when I await for an async function inside of an event listener callback?
content-script.js

chrome.runtime.onMessage.addListener(async (message, sender, sendResponse) => {
 const message1: SendInputMessage = {
    type: EXTENSION_COMMANDS.AC.SEND_INPUT,
    // tabId: get_active_tab_id(EXTENSION_COMMANDS.AC.SEND_INPUT),
    method: "Input.insertText",
    params: {
      text: 'BGAvalue',
    },
  };
  try {
    await chrome.runtime.sendMessage(message1);
  } catch (error) {
    console.error(error);
  }

  return true;
});

background.js

chrome.runtime.onMessage.addListener(async (message: SendInputMessage, sender) => {
  if (message.type !== EXTENSION_COMMANDS.AC.SEND_INPUT) return undefined;
  try {
    const activeTabId = (sender.tab as Tab).id;

    // Check if debugger is not yet attached to the tab.
    const allTabs = await chrome.debugger.getTargets(
      () => {}
    )
    const debuggerIsNotYetAttachedToTab = allTabs.some(
      (target) => target.tabId === activeTabId
    );

    // Attach debugger to the tab.
    const targetTab = {tabId: activeTabId};
    if (debuggerIsNotYetAttachedToTab) {
      const devtoolsProtocolVersion = "1.3";
      await chrome.debugger.attach(targetTab, devtoolsProtocolVersion);
    }

    chrome.debugger.sendCommand(targetTab, message.method, message.params);
  } catch (error) {
    console.error(error);
  }

  return true;
});

And I always get this in both files' consoles when exchanging messages:
image

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions