top of page
  • Sans

How to capture Console Logs (Chrome Extension Manifest v3)

Introduction

The following article explains the logic behind how the Devign Chrome Extension captures console log information by dispatching custom events to content script.



Manifest

In order to use the chrome.scripting API, you need to specify a "manifest_version"of 3 or higher and include the "scripting" permission in your manifest file.



Usage

chrome.scripting API is used to inject JavaScript and CSS into websites. This is similar to what you can do with content scripts, but by using the chrome.scripting API, extensions can make decisions at runtime.



Injection target

The target parameter is used to specify a target to inject JavaScript or CSS into.

Code


Injected code

Extensions can specify the code to be injected either via an external file or a runtime variable.

The following code is the code that we wish to inject at runtime.

Code


Dispatching Custom Events

What the code above is doing - programmatically creating and dispatching events using dispatchEvent() method.

To generate an event programmatically, you follow these steps:

  • First, create a new CustomEvent object.

  • Then, trigger the event using element.dispatchEvent() method.

We are creating a custom event called ‘log’ to capture console logs and passing the log data as a parameter.



src/content/index.tsx (in content scripts)

Send message to the service worker requesting the log data

document.addEventListener('log', (e: any) => {
  chrome.runtime.sendMessage({ setConsoleLog: true, log: e.detail });
});

src/background/index.ts (in service workers)

import { setLogScript } from './log';

async function messageHandler(
  message: any,
  sender: chrome.runtime.MessageSender,
  sendResponse: (response?: any) => void,
) {
		if (message.setLogScript) {
	    if (!sender?.tab?.id) return;
	    setLogScript(sender.tab.id);
	  }
	}


Here’s what it looks like in the Devign Dashboard

Once the console log data has been stored in the backend server, it can be parsed and displayed as shown below.



References:

1. https://developer.chrome.com/docs/extensions/reference/scripting/

2. https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/dispatchEvent

bottom of page