Accessing console and devtools of extension's background.js - debugging

I just started out with Google Chrome extensions and I can't seem to log to console from my background js. When an error occurs (because of a syntax error, for example), I can't find any error messages either.
My manifest file:
{
"name": "My First Extension",
"version": "1.0",
"manifest_version": 2,
"description": "The first extension that I made.",
"browser_action": {
"default_icon": "icon.png"
},
"background": {
"scripts": ["background.js"]
},
"permissions": [
"pageCapture",
"tabs"
]
}
background.js:
alert("here");
console.log("Hello, world!")
When I load the extension, the alert comes up but I don't see anything being logged to console. What am I doing wrong?

You're looking at the wrong place. These console messages do not appear in the web page, but in the invisible background page (ManifestV2) or service worker (ManifestV3).
To view the correct console open devtools for the background script's context:
Visit chrome://extensions/ or right-click the extension icon and select "Manage extensions".
Enable developer mode
Click on the link named background page (ManifestV2) or service worker (ManifestV3).
Screenshot for ManifestV2 extensions:
Screenshot for ManifestV3 extensions:

I had the same problem, in my case the logging was set to "Hide all" in the console tab in Chrome Developer tools.
I had not even realised this was an option, and I can't remember turning it off

For followers who wish to see the debug console for a "content script" of their chrome extension, it is available by doing a normal "show developer console" then use the dropdown arrow to selects its "javascript environment" then you'll have access to its methods, etc.

additionally
if you want to see content_script js file ( when "background" property is not set ) in manifest.json
"content_scripts": [{
"matches": ["<all_urls>"],
"js": ["popup.js"],
}]
"browser_action": {
"default_icon": "icon_32.png",
"default_popup": "popup.html"
}
then right click on extension icon and click on Inspect popup and developer window opens with popup.html opened , there you see console tab.

Similar to the answer of Michiel i also had a funny console configuration: A filter i dont remember setting:
After clearing the filter i saw the messages.

I had this problem as well. It seems as though my webpage was not updating to the newly saved script. This was solved by pressing Ctrl + refresh (or Ctrl + F5) in the chrome browser.

If we want to read messages printed to console from the popup page, we can click the extension icon to open the popup page, then do right click on the popup page anywhere, a dropdown menu will display, we just click "Inspect" menu to open the developer tool. Notice that the popup page must be keep opening. If it is closed(by window.close()), the developer tool will be closed too.

The other answer(s) work(s) for background.js but, if you are looking for console.logs from the popup then you can try:
var bkg = chrome.extension.getBackgroundPage();
bkg.console.log('foo');
I was developing using cra, and this worked for me.

For those developing extensions for Firefox:
TL;DR version: you need to use Ctrl+Shift+J to call up the browser console window, and click on the settings icon on the top right-hand corner and make sure that "Show Content Messages" is checked.
Longer explanation from a related stackoverflow question: How do I see the console.log output of a background script in a Firefox WebExtension?

Related

Start karma tests in Firefox without privacy notice tab and disable extensions

I am using the karma-firefox-launcher plugin to launch my karama tests in Firefox, which works just fine. However every time it launches, Firefox seems to think this is a first-run and it also opens tabs for the privacy notice page, and another one for an extension.
This is what I see every time I run the tests
I was able to make a custom launcher for Firefox in my karma config file to start it in safe mode, like this:
customLaunchers: {
firefox_custom: {
base: 'Firefox',
flags: ["-safe-mode"]
},
},
Which works, but now it shows this dialog every time (which requires the button to be clicked to continue) and is is equally annoying
In my attempt to disable the privacy notice tab, I've tried setting these preferences, but none have worked. Perhaps I'm not setting them correctly?
flags: ["-pref='app.normandy.first_run=false'"]
and
flags: ["-pref='datareporting.policy.firstRunURL='"]
What CLI flags can I set here to both disable extensions without the additional dialog, and stop the privacy
According to the karma-firefox-launcher docs, you can set preferences directly, so after browsing around in the firefox about:config page and searching for "firstrun" I found a preference named toolkit.telemetry.reportingpolicy.firstRun
So, the following will work to prevent that privacy notice tab from opening, but the Adobe Acrobat extension "welcome" tab still opens.
firefox_custom: {
base: 'Firefox',
prefs: {
'toolkit.telemetry.reportingpolicy.firstRun': false,
}
},
It's improved but not all the way there yet! I'll update this answer if I find anything else out.

Debugging Chrome extension with access to chrome.devtools api

I am beginner in Chrome extensions development. I need to extend existing extension (angularjs-batarang), but I have some problems with debugging.
manifest.json has entries:
"background": {
"page": "background.html"
},
"devtools_page": "devtoolsBackground.html"
The question is: how to debug devtools_page? I added to manifest.json additional entry
"options_page": "devtoolsBackground.html" and when I add this extension to Chrome I have possibility to run options page from chrome://extensions.
It works because application stops at breakpoints. But unfortunatelly I have no access to chrome.devtools API. So it is not solution.
How can I debug this and have access to this API?
To open the developer tools for a devtools page, I usually follow the following steps:
Open the developer tools.
Undock the developer tools if not already done (via the button in the bottom-left corner).
Press Ctrl + Shift + J to open the developer tools of the developer tools.
Optional: Feel free to dock the developer tools again if you had undocked it at step 2.
Switch from "<top frame>" to devtoolsBackground.html (or whatever name you have chosen for your devtools). (example)
Now you can use the Console tab to play with the chrome.devtools API.

What can I do with Firefox's Browser Console which I can't with Web Console?

I have recently known that Firefox has a Browser Console (different than Web Console) which can be enabled setting devtools.chrome.enabled to true.
I have searched information about what can I do with it, but I have only found
The Browser Console lets you see all JavaScript errors and logging in
the browser, including from Firefox code. To enable it, go to
about:config in the url bar and set devtools.chrome.enabled to true.
Activate it through with the menu Web Developer > Browser Console.
(https://developer.mozilla.org/en-US/docs/Debugging_JavaScript#Browser_Console)
I have discovered that Browser console is useful because I can see the errors in sandboxed GreaseMonkey scripts. But I guess it can do lots of interesting things, where can I find some info?
This MDN page says it all (when I asked this question that page didn't exist, it was created the Aug 7, 2013 5:04:27 PM)
Browser Console
The Browser Console is like the Web Console, but applied to the whole
browser rather than a single content tab.
So it logs the same sorts of information as the Web Console - network
requests, JavaScript, CSS, and security errors and warnings, and
messages explicitly logged by JavaScript code. However, rather than
logging this information for a single content tab, it logs information
for all content tabs, for add-ons, and for the browser's own code.
Similarly, you can execute JavaScript expressions using the Browser
Console. But while the Web Console executes code in the page window
scope, the Browser Console executes them in the scope of the browser's
chrome window. This means you can interact with all the browser's tabs
using the gBrowser global, and even with the XUL used to specify the
browser's user interface.
To open the Browser Console, select "Browser Console" from the Web
Developer submenu in the Firefox Menu (or Tools menu if you display
the menu bar or are on Mac OS X):
You can see that the Browser Console looks and behaves very much like
the Web Console:
most of the window is occupied by a pane that display messages
at the top, a toolbar enables you to filter the messages that appear
at the bottom, a command line interpreter enables you to evaluate JavaScript expressions.
Browser Console logging
The Browser console logs the same sorts of messages as the Web
Console:
HTTP requests
Warnings and errors (including JavaScript, CSS, security warnings and errors, and messages explicitly logged by JavaScript code using
the console API)
Input/output messages: commands send to the browser via the command line, and the result of executing them.
However, it displays such messages from:
web content hosted by all browser tabs
the browser's own code
add-ons.
Messages from add-ons
The Browser Console displays messages
logged by all Firefox add-ons.
For example, here's a very simple Add-on SDK add-on that just
logs an error when the user clicks an icon:
// base-64 encoded icon, from http://edmerritt.com/'s "Vaga" icon set
var icon = "data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAYAAAAf8/9" +
"hAAAC90lEQVR4Xk1STUgbWxQ+mbmZNGqcJGjaGBq7UUGpYCEUXMSFLgRBdKeIG6F06aKUt6irEks" +
"R3JjWGAquSjeW8p6g3UQeCPKeJvCgRYP4QxK0TaPPGJPMZMzM3J4bM9ED35x7z/nOud+9c0yKooBh" +
"h6FQV1lRZmRZ9l8riksplQjhedVssWQQm4SQwOMXL3YNviAIwBmb/WDwVT6X+1snZMz18GFLe3s7e" +
"dLdDR2dncTl9bZQjhvD/D//zc+/gTtGjGJJkv5wtrTYHLIMaioFFL2sqgA8D3VWK9gcDjhvbLRlUq" +
"mX38LhB93Pn08BGnewuNhVyOennW63zX5xAdfJJKiXl6Di1ewTExWvZrNQwriYz4PT4yH/Hx9PHm5" +
"s3DRQ8M5CQ0OzXZKgnMmAjqfqmBBHRqC+pwcco6OgUQoaxhXMO3QdiMVCsvH462Qy2UxKkuTHO4N2" +
"clIh6UimABVA1bOYztaYB1TpvH8fThMJj1vTholcLLqsHAeqJN0Wo9dwz0wtFkFjC6MRxus9Hrj68" +
"QM0TRsgiiQRARtI2J0yQpVYzuVuGqA3VFCGchnqzGaQrq5A13Uf4fE/lzSNUJ4HDZMGObu1xXArv6" +
"rOhDy5VALzvXtMQSvHC0Imz4YJA4ysVQvE3l7oCAaZZ/EaTPhLc4UC1DU1sQZJTsAJO0+ngXM6Qef" +
"5mgKusRGY8aJYK2YqCfLSiQSIbW3sClGOx/EsZLP5M10Hs8sFOsdVyL/W1yERCkF6ba1WLGD+Fz6q" +
"xObh6VOmIML5ZmZ26x2Odz+PjtRzfBzB6wXebgeTIEBubw/AYgEz7q2PHsE5HnK6vw/uvj7gRPEvV" +
"LAKOEgVbL59u/zl2bPy2vQ03Z6bo7vBID0Ih+n3hQW6NTtLMUc/jo/TjaUlGovFtqPRaD97WFZcQ2" +
"xlZSoSCJx8RvLy0BB97/fTD4OD9NPkJP0aCNB/IxGKhX/u7Oz0Mz5rYGKfuxaPx5tR2jBiAHM+9K2" +
"IJK6jiAhi1efznRn837fI5BVWw7NCAAAAAElFTkSuQmCC";
widget = require("sdk/widget").Widget({
id: "an-error-happened",
label: "Error!",
contentURL: icon,
onClick: logError
});
function logError() {
console.error("something went wrong!");
}
If you build this as an XPI file, then open the Browser Console,
then open the XPI file in Firefox and install it, you'll see an icon
in the Add-on bar:
Click the icon. You'll see output like this in the Browser Console:
For Add-on SDK-based add-ons only, the message is prefixed with the
name of the add-on ("log-error"), making it easy to find all messages
from this add-on using the "Filter output" search box. By
default, only error messages are logged to the console, although you
can change this in the browser's preferences.
Browser Console command line
Like the Web Console, the command line interpreter enables you to
evaluate JavaScript expressions in real time:
Also like the Web Console's command line interpreter, this command
line supports autocomplete, history, and various keyboard shortcuts
and helper commands. If the result of a command is an object, you can click on the object to see its details.
But while the Web Console executes code in the scope of the content
window it's attached to, the browser console executes code in the
scope of the chrome window of the browser. You can confirm this by
evaluating window:
This means you can control the browser: opening, closing tabs and
windows and changing the content that they host, and modify the
browser's UI by creating, changing and removing XUL elements.
Controlling the browser
The command line interpreter gets access to the tabbrowser object,
through the gBrowser global, and that enables you to control the
browser through the command line. Try running this code in the Browser
Console's command line (remember that to send multiple lines to the
Browser Console, use Shift+Enter):
var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.selectedTab);
newTabBrowser.addEventListener("load", function() {
newTabBrowser.contentDocument.body.innerHTML = "<h1>this page has been eaten</h1>";
}, true);
newTabBrowser.contentDocument.location.href = "https://mozilla.org/";
It adds a listener to the currently selected tab's load event that
will eat the new page, then loads a new page.
Modifying the browser UI
Since the global window object is the browser's chrome window, you can
also modify the browser's user interface. On Windows, the following
code will add a new item to the browser's main menu:
var parent = window.document.getElementById("appmenuPrimaryPane");
var makeTheTea = gBrowser.ownerDocument.defaultView.document.createElementNS("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul", "menuitem");
makeTheTea.setAttribute("label", "A nice cup of tea?");
parent.appendChild(makeTheTea);
On OS X, this similar code will add a new item to the "Tools" menu:
var parent = window.document.getElementById("menu_ToolsPopup");
var makeTheTea = gBrowser.ownerDocument.defaultView.document.createElementNS("http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul", "menuitem");
makeTheTea.setAttribute("label", "A nice cup of tea?");
parent.appendChild(makeTheTea);

In Firefox, console.log is not showing anything

I'm trying a simple console.log function in Firefox:
console.log("Hello, World!");
You may try it on: http://jsfiddle.net/EkZjK/
You may also try the full code in a stand-alone HTML file:
<html>
<head>
<meta content="text/html;charset=utf-8" http-equiv="Content-Type">
<script type="text/javascript">
console.log("Hello World !");
</script>
</head>
</html>
I get console logs in Chrome.
But in Firefox I cannot see the logs.
I tried the Firebug console and Ctrl + Shift + J.
Both don't show the log message in Firefox.
PS: I restarted Firefox, restarted Windows, tried on another machine, deleted the Firefox profile and created another one, and reinstalled Firefox. But the problem still exists.
How can I solve this?
For some previous versions of Firefox
I had the same problem with a different root cause.
Hit Ctrl + Shift + K to open the full console. In the second row from the top there are tabs - Net, CSS, JS, Security, Logging, and Server. Hit the triangle to the right of "Logging" to open the dropdown and make sure that at least "log" is on.
Reinstalling the Firebug plugin solved the issue.
Now it appears in the Firebug console (not in Ctrl + Shift + J).
For Firefox 77.0.1 and Ubuntu 18.04 (Bionic Beaver) LTS (Bionic Beaver):
I had the same problem.
Open the Firefox console - Ctrl + Shift + J.
In the browser console, click on the top right settings icon. In the dropdown, click on Show Content Messages.
Then console.log messages will start showing up in the console.
Uninstall Firebug (or disable it)
Press F12 and enjoy the console.
The problem is Firebug. It's not maintained anymore and may be unstable (see the official page). Other users here recommend to update it, but it may not work, or work until the next Firefox update.
I had this problem in Firefox 71, and I found that when you open the console not everything is automatically logged.
When you go to the right side of the console you see a number of buttons, (Errors, Warnings, Logs, Info, Debug, CSS, XHR, and Requests). Enable all logs by clicking these buttons.
I had the same problem with Firefox 75.0 on Ubuntu 18.0 (Bionic Beaver). The following solved it for me:
Open the Console
Click the Logs button until grey in Filter output row on the right
Click the Settings gear on the right and choose in the dropdown "Persist Logs".
I had the problem again today with Chrome and Firefox.
Ultimately, however, the cause was not the console, but some code in jQuery UI v1.12.1.
After I had written console.clear() after the jQuery UI code, the console outputs after this script were shown again.
I recently had the same issue with Firefox. What worked for me was restarting Firefox and then adding the Console.clear() method to my script. Once the page loads up, the console logs your messages again.
In FireFox 90.0, Mac OS 11.4, I had to click on the Gear Icon and put a check mark next to 'Show Content Messages' before console.log output appeared on the console.
Edit: I see now this was mentioned in the fine print on one of the responses above.
I had the same problem with my browser but all you’ll have to do is to open up the console by pressing ctrl + shift + k or press the right key and press inspect then navigate to the left hand section that says logs click on it and you should be good to go

Where my log statement is printing on Mac?

I have an firefox extension with the name myjavascriptfile.js,As I am new to this addon concepts,just I want to debug this script.So I am using the following statements in this file like
function LOG(text)
{
var consoleService = Components.classes["#mozilla.org/consoleservice;1"].getService(Components.interfaces.nsIConsoleService);
consoleService.logStringMessage(text);
}
observe: function(subject, topic, data)
{
LOG("observe called ");
}
I know this observe is getting called but I dont know where to see my log message.can some one tell me Where it is printing?
Please help.
That text goes to the Error Console. You might need to go to about:config and change devtools.errorconsole.enabled preference to true - the Error Console was removed from the menus by default while ago (strangely enough, I could still see it even without this pref). I think that on OS X you can still open the Error Console via Tools / Web Developer menu, on Windows you have to click the Firefox button and choose Web Developer menu there. Alternatively, Command-Shift-J should do as well.

Resources