- Javascript in firefox console
- Консоль разработчика
- Google Chrome
- Firefox, Edge и другие
- Safari
- Итого
- Browser Console¶
- Opening the Browser Console¶
- Browser Console logging¶
- Messages from add-ons¶
- Console.sys.mjs¶
- Browser Console command line¶
- Controlling the browser¶
- this page has been eaten
- Modifying the browser UI¶
Javascript in firefox console
JavaScript Tutorials — Herong’s Tutorial Examples — 2.33, by Herong Yang
∟ JavaScript Console in Mozilla Firefox
This section provides tutorial example on how to use the JavaScript Console in Mozilla Firefox to view execution errors and log messages resulted from JavaScript execution. You can also use it to run any JavaScript statements to interact with the HTML document.
What is JavaScript Console in Mozilla Firefox? JavaScript Console in Mozilla Firefox is a console provided by the browser for you:
- To see any errors or log messages generated by the browser when executing embedded JavaScript codes.
- To run any JavaScript code to interact with the Web document interactively.
Here is what I did to test the JavaScript Console in Mozilla Firefox:
1. Run Mozilla Firefox and load the following HTML code:
2. Press F12 key. I see the developer panel displayed on the screen.
3. Click «Console» tab on the developer panel. I see the console log message displayed: «Hello World! — Console».
4. Enter some JavaScript statements in the console to run:
Hello World! — Console >> var msg = document.title; < undefined >> console.log(msg.length); 12
Cool. The console is nice tool to troubleshoot any issues with my JavaScript code in HTML pages running on Mozilla Firefox.
Консоль разработчика
Код уязвим для ошибок. И вы, скорее всего, будете делать ошибки в коде… Впрочем, давайте будем откровенны: вы точно будете совершать ошибки в коде. В конце концов, вы человек, а не робот.
Но по умолчанию в браузере ошибки не видны. То есть, если что-то пойдёт не так, мы не увидим, что именно сломалось, и не сможем это починить.
Для решения задач такого рода в браузер встроены так называемые «Инструменты разработки» (Developer tools или сокращённо — devtools).
Chrome и Firefox снискали любовь подавляющего большинства программистов во многом благодаря своим отменным инструментам разработчика. Остальные браузеры, хотя и оснащены подобными инструментами, но всё же зачастую находятся в роли догоняющих и по качеству, и по количеству свойств и особенностей. В общем, почти у всех программистов есть свой «любимый» браузер. Другие используются только для отлова и исправления специфичных «браузерозависимых» ошибок.
Для начала знакомства с этими мощными инструментами давайте выясним, как их открывать, смотреть ошибки и запускать команды JavaScript.
Google Chrome
В её JavaScript-коде закралась ошибка. Она не видна обычному посетителю, поэтому давайте найдём её при помощи инструментов разработки.
Нажмите F12 или, если вы используете Mac, Cmd + Opt + J .
По умолчанию в инструментах разработчика откроется вкладка Console (консоль).
Она выглядит приблизительно следующим образом:
Точный внешний вид инструментов разработки зависит от используемой версии Chrome. Время от времени некоторые детали изменяются, но в целом внешний вид остаётся примерно похожим на предыдущие версии.
- В консоли мы можем увидеть сообщение об ошибке, отрисованное красным цветом. В нашем случае скрипт содержит неизвестную команду «lalala».
- Справа присутствует ссылка на исходный код bug.html:12 с номером строки кода, в которой эта ошибка и произошла.
Под сообщением об ошибке находится синий символ > . Он обозначает командную строку, в ней мы можем редактировать и запускать JavaScript-команды. Для их запуска нажмите Enter .
Обычно при нажатии Enter введённая строка кода сразу выполняется.
Чтобы перенести строку, нажмите Shift + Enter . Так можно вводить более длинный JS-код.
Теперь мы явно видим ошибки, для начала этого вполне достаточно. Мы ещё вернёмся к инструментам разработчика позже и более подробно рассмотрим отладку кода в главе Отладка в браузере.
Firefox, Edge и другие
Инструменты разработчика в большинстве браузеров открываются при нажатии на F12 .
Их внешний вид и принципы работы мало чем отличаются. Разобравшись с инструментами в одном браузере, вы без труда сможете работать с ними и в другом.
Safari
Safari (браузер для Mac, не поддерживается в системах Windows/Linux) всё же имеет небольшое отличие. Для начала работы нам нужно включить «Меню разработки» («Developer menu»).
Откройте Настройки (Preferences) и перейдите к панели «Продвинутые» (Advanced). В самом низу вы найдёте чекбокс:
Теперь консоль можно активировать нажатием клавиш Cmd + Opt + C . Также обратите внимание на новый элемент меню «Разработка» («Develop»). В нем содержится большое количество команд и настроек.
Итого
- Инструменты разработчика позволяют нам смотреть ошибки, выполнять команды, проверять значение переменных и ещё много всего полезного.
- В большинстве браузеров, работающих под Windows, инструменты разработчика можно открыть, нажав F12 . В Chrome для Mac используйте комбинацию Cmd + Opt + J , Safari: Cmd + Opt + C (необходимо предварительное включение «Меню разработчика»).
Теперь наше окружение полностью настроено. В следующем разделе мы перейдём непосредственно к JavaScript.
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.
If you also want to use the other web developer tools in the regular Web Toolbox with add-on or browser code, consider using the Browser Toolbox .
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.
NB: The Browser Console command line (to execute JavaScript expressions) is disabled by default. To enable it set the devtools.chrome.enabled preference to true in about:config, or set the “Enable browser chrome and add-on debugging toolboxes” (Firefox 40 and later) option in the developer tool settings .
Opening the Browser Console¶
You can open the Browser Console in one of two ways:
- from the menu: select “Browser Console” from the Browser Tools submenu in the Firefox Menu (or Tools menu if you display the menu bar or are on macOS).
- from the keyboard: press Ctrl + Shift + J (or Cmd + Shift + J on a Mac).
You can also start the Browser Console by launching Firefox from the command line and passing the -jsconsole argument:
/Applications/FirefoxAurora.app/Contents/MacOS/firefox-bin -jsconsole
The Browser Console looks like this:
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.
Beginning with Firefox 68, the Browser Console allows you to show or hide messages from the content process (i.e. the messages from scripts in all the opened pages) by setting or clearing the checkbox labeled Show Content Messages. The following image shows the browser console focused on the same page as above after clicking on the Show Content Messages checkbox.
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:
Messages from add-ons¶
The Browser Console displays messages logged by all Firefox add-ons.
Console.sys.mjs¶
To use the console API from a traditional or bootstrapped add-on, get it from the Console module.
One exported symbol from Console.sys.mjs is console . Below is an example of how to access it, which adds a message to the Browser Console.
const console > = ChromeUtils.importESModule("resource://gre/modules/Console.sys.mjs"); console.log("Hello from Firefox code"); //output messages to the console
Browser Console command line¶
The Browser Console command line is disabled by default. To enable it set the devtools.chrome.enabled preference to true in about:config , or set the “Enable chrome debugging” option in the developer tool settings .
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 = "this page has been eaten
"; >, 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.
You can restart the browser with the command Ctrl + Alt + R (Windows, Linux) or Cmd + Alt + R (Mac) This command restarts the browser with the same tabs open as before the restart.
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 macOS, 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);