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

JavascriptGoogle ChromeGoogle Chrome-Extension

Javascript Problem Overview


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?

Javascript Solutions


Solution 1 - Javascript

You can open the background page's console if you click on the "background.html" link in the extensions list.

To access the background page that corresponds to your extensions open Settings / Extensions or open a new tab and enter chrome://extensions. You will see something like this screenshot.

Chrome extensions dialogue

Under your extension click on the link background page. This opens a new window. For the context menu sample the window has the title: _generated_background_page.html.

Solution 2 - Javascript

Any extension page (except content scripts) has direct access to the background page via chrome.extension.getBackgroundPage().

That means, within the popup page, you can just do:

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

To make it easier to use:

var bkg = chrome.extension.getBackgroundPage();
bkg.console.log('foo');

Now if you want to do the same within content scripts you have to use Message Passing to achieve that. The reason, they both belong to different domains, which make sense. There are many examples in the Message Passing page for you to check out.

Hope that clears everything.

Solution 3 - Javascript

To answer your question directly, when you call console.log("something") from the background, this message is logged, to the background page's console. To view it, you may go to chrome://extensions/ and click on that inspect view under your extension.

When you click the popup, it's loaded into the current page, thus the console.log should show log message in the current page.

Solution 4 - Javascript

You can still use console.log(), but it gets logged into a separate console. In order to view it - right click on the extension icon and select "Inspect popup".

Solution 5 - Javascript

The simplest solution would be to add the following code on the top of the file. And than you can use all full Chrome console api as you would normally.

 console = chrome.extension.getBackgroundPage().console;
// for instance, console.assert(1!=1) will return assertion error
// console.log("msg") ==> prints msg
// etc

Solution 6 - Javascript

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

Open log:

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

Solution 7 - Javascript

Try this, if you want to log to the active page's console:

chrome.tabs.executeScript({
	code: 'console.log("addd")'
});

Solution 8 - Javascript

In relation to the original question I'd like to add to the accepted answer by Mohamed Mansour that there is also a way to make this work the other way around:

You can access other extension pages (i.e. options page, popup page) from within the background page/script with the chrome.extension.getViews() call. As described here.

 // overwrite the console object with the right one.
var optionsPage = (  chrome.extension.getViews()  
                 &&  (chrome.extension.getViews().length > 1)  ) 
                ? chrome.extension.getViews()[1] : null;

 // safety precaution.
if (optionsPage) {
  var console = optionsPage.console;
}

Solution 9 - Javascript

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...)

Solution 10 - Javascript

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!!

Solution 11 - Javascript

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

Solution 12 - Javascript

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

Solution 13 - Javascript

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.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionHailwoodView Question on Stackoverflow
Solution 1 - JavascriptsergView Answer on Stackoverflow
Solution 2 - JavascriptMohamed MansourView Answer on Stackoverflow
Solution 3 - JavascriptsongyyView Answer on Stackoverflow
Solution 4 - JavascriptLachoTomovView Answer on Stackoverflow
Solution 5 - Javascriptdd .View Answer on Stackoverflow
Solution 6 - JavascriptO FallanteView Answer on Stackoverflow
Solution 7 - JavascriptFazView Answer on Stackoverflow
Solution 8 - JavascriptWoodrowShigeruView Answer on Stackoverflow
Solution 9 - JavascriptDenis G.View Answer on Stackoverflow
Solution 10 - JavascriptAnushka RaiView Answer on Stackoverflow
Solution 11 - JavascriptMichal SView Answer on Stackoverflow
Solution 12 - JavascriptEricgitView Answer on Stackoverflow
Solution 13 - JavascriptCarsonView Answer on Stackoverflow