google chrome extension :: console.log() from background page?

Viewed 176526

If I call console.log('something'); from the popup page, or any script included off that it works fine.

However as the background page is not directly run off the popup page it is not included in the console.

Is there a way that I can get console.log()'s in the background page to show up in the console for the popup page?

is there any way to, from the background page call a function in the popup page?

13 Answers
const log = chrome.extension.getBackgroundPage().console.log;
log('something')

Open log:

  • Open: chrome://extensions/
  • Details > Background page

It's an old post, with already good answers, but I add my two bits. I don't like to use console.log, I'd rather use a logger that logs to the console, or wherever I want, so I have a module defining a log function a bit like this one

function log(...args) {
  console.log(...args);
  chrome.extension.getBackgroundPage().console.log(...args);
}

When I call log("this is my log") it will write the message both in the popup console and the background console.

The advantage is to be able to change the behaviour of the logs without having to change the code (like disabling logs for production, etc...)

To get a console log from a background page you need to write the following code snippet in your background page background.js -

 chrome.extension.getBackgroundPage().console.log('hello');

Then load the extension and inspect its background page to see the console log.

Go ahead!!

Curently with Manifest 3 and service worker, you just need to go to Extensions Page / Details and just click Inspect Views / Service Worker.

To view console while debugging your chrome extension, you should use the chrome.extension.getBackgroundPage(); API, after that you can use console.log() as usual:

chrome.extension.getBackgroundPage().console.log('Testing');

This is good when you use multiple time, so for that you create custom function:

  const console = {
    log: (info) => chrome.extension.getBackgroundPage().console.log(info),
  };
  console.log("foo");

you only use console.log('learnin') everywhere

chrome.extension.getBackgroundPage() I get null

and accrouding documentation,

Background pages are replaced by service workers in MV3.

  • Replace background.page or background.scripts with background.service_worker in manifest.json. Note that the service_worker field takes a string, not an array of strings.

manifest.json

{
  "manifest_version": 3,
  "name": "",
  "version": "",
  "background": {
    "service_worker": "background.js"
  }
}

anyway, I don't know how to use getBackgroundPage, but I found another solution as below,

Solution

use the chrome.scripting.executeScript

So you can inject any script or file. You can directly click inspect (F12) and can debug the function.

for example

chrome.commands.onCommand.addListener((cmdName) => {
    switch (cmdName) {
      case "show-alert":
        chrome.storage.sync.set({msg: cmdName}) // You can not get the context on the function, so using the Storage API to help you. // https://developer.chrome.com/docs/extensions/reference/storage/
        chrome.tabs.query({active: true, currentWindow: true}).then(([tab])=>{
          chrome.scripting.executeScript({
            target: {tabId: tab.id},
            function: () => {
              chrome.storage.sync.get(['msg'], ({msg})=> {
                console.log(`${msg}`)
                alert(`Command: ${msg}`)
              })
            }
          })
        })
        break
      default:
        alert(`Unknown Command: ${cmdName}`)
    }
  })

I create an open-source for you reference.

Related