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

后端 未结 11 1954

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

相关标签:
11条回答
  • 2020-11-30 17:44

    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 讨论(0)
  • 2020-11-30 17:47

    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;
    }
    
    0 讨论(0)
  • 2020-11-30 17:49

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

    0 讨论(0)
  • 2020-11-30 17:50

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

    0 讨论(0)
  • 2020-11-30 17:52
    const log = chrome.extension.getBackgroundPage().console.log;
    log('something')
    

    Open log:

    • Open: chrome://extensions/
    • Details > Background page
    0 讨论(0)
提交回复
热议问题