262

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?

3
  • 1
    What do you mean exactly by saying "it works fine"? Where are reading "something"? Using console.log() in a popup window shouldn't print in loaded page's console - since the question is 2 years old did the API change?
    – anddam
    Commented Nov 28, 2012 at 9:48
  • 29
    if you right click -> inspect popup on your browser action, you'll get a developer tools page for your extension. popup.js will print logs to that. Commented Jul 3, 2013 at 21:51
  • @not_shitashi's comment should be the answer to this question.
    – gabe
    Commented Feb 4, 2018 at 17:36

13 Answers 13

247

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.

7
  • 4
    Cheers, I am aware of this, however opening the background page directly does not invoke anything from the popup page.
    – Hailwood
    Commented Oct 2, 2010 at 3:14
  • 1
    Opening background page doesn't output any console logging information.
    – Layke
    Commented Oct 26, 2012 at 13:03
  • @Hailwood opening the background page doesn't invoke anything but will show the console for background page.
    – anddam
    Commented Nov 28, 2012 at 22:31
  • 1
    @Layke once you opened the background page you still have to write into it, i.e. directly use console.log() from the background page or, as mohamed-mansour said, calling the same method on the object returned by getBackgroundPage()
    – anddam
    Commented Nov 28, 2012 at 22:34
  • 3
    I found this question searching how to check an extension output (like OP) and found this answer very useful since it allowed me to check the console logging without passing through a content page.
    – anddam
    Commented Nov 28, 2012 at 22:36
193

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.

3
  • 4
    @MohamedMansour, this solution does not work for me. If I alert() chrome.extension.getBackgroundPage(), I get null. Do I need to have permissions set or some other configuration?
    – jds
    Commented Oct 22, 2014 at 22:33
  • @gwg does your extension have a background page? According to the documentation "Returns null if the extension has no background page." developer.chrome.com/extensions/… Commented Dec 17, 2014 at 22:32
  • This works perfectly for my own messages to console. Thanks. Any thoughts on how to also make exceptions etc from popup.js appear in background.js's console? Commented Aug 18, 2015 at 2:45
81

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.

2
  • 1
    my extension does not have that, other extensions do however ! how do I enable it
    – Ahmed Eid
    Commented May 28, 2017 at 22:22
  • 1
    If you have 3 monitors like me...swivel your head. It was opening ChromeDevTools on the opposite end of my monitor array and I didn't see it.
    – mpen
    Commented Apr 13, 2019 at 20:05
61

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

0
18

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
0
14
const log = chrome.extension.getBackgroundPage().console.log;
log('something')

Open log:

  • Open: chrome://extensions/
  • Details > Background page
1
  • 2
    Would you mind providing some more explanations to your commands? Commented Feb 12, 2019 at 19:13
11

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

chrome.tabs.executeScript({
    code: 'console.log("addd")'
});
2
  • 1
    Requires host permissions for the current tab.
    – Xan
    Commented Aug 11, 2014 at 8:10
  • 1
    You can add it for testing, and remove if you release the addon.
    – Faz
    Commented Aug 14, 2014 at 1:32
10

Update for 2022: with Manifest 3 and service worker, you just need to go to chrome://extensions click details button on your extension, find: Inspect Views -> Service Worker.

4

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

3

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;
}
2

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.

1

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.

0

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.