简体   繁体   中英

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

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?

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 扩展程序对话框

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 .

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.

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.

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

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

Open log:

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

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

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

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

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

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

目前使用 Manifest 3 和 Service Worker,您只需要转到Extensions Page / Details并单击Inspect Views / Service Worker

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM