working - javascript chrome extension




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

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?


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.


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

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

Throwing obvious answer here just in case. You know that you can open background page's console if you click on "background.html" link in the extensions list, right?

Edit

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.

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.


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

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

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







google-chrome-extension