The Wayback Machine - https://web.archive.org/web/20150906073243/https://developer.mozilla.org/ru/docs/Tools/Web_Console

Веб-консоль

by 5 contributors:

This translation is incomplete. Please help translate this article from English.

Веб-консоль:

  1. Логирование информации, связанной с веб-страницей: любые сетевые запросы, ошибки и предупреждения JavaScript и CSS, а также сообщения об ошибках, предупреждения и информационные сообщения, выдаваемые кодом JavaScript работающим в контексте страницы;
  2. Предоставляет Вам возможность взаимодействовать с веб-страницей выполняя в её контексте выражения JavaScript.

Это часть замены старой Консоли Ошибок, встроенной в Firefox. Старая Консоль Ошибок выводила ошибки, предупреждения и сообщения от всех веб-страниц, ошибки самого выполнения самого браузера и его дополнений. Из-за этого было трудно выделить, сообщения от конкретной страницы. Новая Веб-консоль всегда привязана к определенной веб-странице и показывает только связанную с ней информацию.

Другая половина замены Консоли ошибок — Консоль браузера, которая выводит ошибки, предупреждения и сообщения от кода браузера и от дополнений.

Как открыть Веб Консоль

Чтобы открыть Веб-консоль, выберите «Веб-консоль» в меню (Веб-)разработка в Меню Firefox (или меню Инструменты, если Вы настроили показывать панель меню или Вы работаете на Mac OS X), или нажмите её комбинацию клавиш CtrlShiftK (CommandOptionK в OS X).

Внизу окна браузера появится Набор инструментов с выбранной Веб-консолью (в Панели инструментов разработчика она называется просто «Консоль»):

Под панелью инструментов окна инструментов разработчика, интерфейс веб-консоли разделён на три части:

  • Панель инструментов: вдоль верхнего края — панель инструментов с кнопками типа «Сеть» ("Net"), «CSS» и «JS». Эта панель — для фильтрации выводимых сообщений.
  • Командная строка: вдоль нижнего края — командная строка, в которую можно вводить выражения JavaScript
  • Поле вывода сообщений: между панелью инструментов и командной строкой, занимая большую часть окна, располагается пространство, в которое Веб-консоль выводит сообщения.

Поле вывода сообщений

Большую часть Веб-консоли занимает поле вывода сообщений:

В поле вывода сообщений можно увидеть:

Каждое сообщение показывается в отдельной строке:

Время Время когда сообщение было записано. Начиная с Firefox 28 и новее, по умолчанию время сообщения не выводится. Но при необходимости можно изменить это поведение активировав вывод времени в настроках Инструментов.
Категория

Категория: указывает на тип сообщения:

  • чёрный: HTTP-запрос
  • голубой: CSS: предупреждения/ошибки/лог
  • оранжевый: JavaScript: предупреждения/ошибки
  • красный: безопасность: предупреждения/ошибки
  • светло-серый: сообщения которые выводятся в консоль с помощью консольного API cс использование  кода JavaScript
  • Dark Gray: input/output из интерфейса интерпретатора командной строки
Тип Для все сообщений за исключением HTTP запросов и интерактивного input/output, иконка обозначает тип сообщения, то ли это ошибкаr(X), предупреждение(!), или просто информационного сообщение(i).
Сообщение Само сообщение.
Количество повторов Если строка которая генерирует предупреждение или ошибку выполняется больше одного раза, то на поле сообщений она попадет только один раз, но рядом появится счётчик который укажет сколько раз это сообщение было выведено в поле сообщений.
Имя файля и номер строки

Для сообщений JavaScript, CSS, и консольного API, можно отследить строку с кодом которая стала причиной этого сообщения. Консоль также покажет ссылку на файл и номер строки ставшей причиной сообщения..

Начиная с Firefox 36, сообщение также включает в себя в номер колонки в строке.

По умолчанию консоль очищается каждый раз когда вы открываете новую страницу или перезагружает текущую. Чтобы переопределить это поведение, активируйте опцию "Enable persistent logs" в Настройках.

HTTP запросы

HTTP запросы записываются следующим образом:

Время Время записи сообщения
Категория Показывает что сообщение является HTTP запросом.
Метод Вид запроса HTTP
URI целевая ссылка URI
Резюме Версия и статус HTTP протокола, время выполнения запроса.

 

Нажав мышкой на сообщение вы увидите следующее окно с более детальной информацией о запросе и ответе на него:

Scrolling down reveals the response headers. By default, the Web Console does not log request and response bodies: to do this, activate the context menu in the Web Console and select "Log Request and Response Bodies", reload the page, and you'll then see them in the "Inspect Network Request" window.

Only the first megabyte of data is logged for each request or response body, so very large requests and responses will be truncated.

Network log messages are not shown by default. Use the filtering feature to show them.

XHR

From Firefox 38 onwards, the Web Console indicates when a network request was made as an XMLHttpRequest:

Also from Firefox 38 onwards, you can filter the network requests so as to only see XMLHttpRequests.

Like normal network request log messages, logs of XMLHttpRequests are not shown by default. Use the filtering feature to show them.

JavaScript errors and warnings

JavaScript messages look like this:

CSS errors, warnings, and reflow messages

CSS messages look like this:

By default, CSS warnings and log messages are not shown.

Reflow events

The Web Console also logs reflow events under the CSS category. A reflow is the name given to the operation in which the browser calculates the layout of all or part of the page. Reflows occur when a change has happened to a page that the browser thinks affects the layout. Many events can trigger reflows, including: resizing the browser window, activating pseudoclasses like :hover, or manipulating the DOM in JavaScript.

Because reflows can be computationally expensive and directly affect the user interface, they can have a big impact on the responsiveness of a website or web app. By logging reflow events the Web Console can give you insight into when reflow events are being triggered, how long they take to execute and, if the reflows are synchronous reflows triggered from JavaScript, which code triggered them.

Reflow events are logged as "Log" messages, as distinct from CSS errors or warnings. By default, they are disabled. You can enable them by clicking the "CSS" button in the toolbar and selecting "Log".

Each message is labeled "reflow" and shows the time taken to execute the reflow:

If the reflow is a synchronous reflow triggered from JavaScript, it also shows a link to the line of code that triggered the reflow:

Click the link to open the file in the Debugger.

Synchronous and asynchronous reflows

If a change is made that invalidates the current layout - for example, the browser window is resized or some JavaScript modifies an element's CSS - the layout is not recalculated immediately. Instead, the reflow happens asynchronously, the next time the browser decides it needs to be done (generally, the next time the browser repaints). In this way the browser can save up a collection of invalidating changes and recalculate their effect at once.

However, if some JavaScript code reads a style that has been modified, then the browser must perform a synchronous reflow in order to calculate the computed style to return. For example, code like this will cause an immediate, synchronous, reflow, when it calls window.getComputedStyle(thing).height:

var thing = document.getElementById("the-thing");
thing.style.display = "inline-block";
var thingHeight = window.getComputedStyle(thing).height;

Because of this, it's a good idea to avoid interleaving write and read calls to an element's styles when manipulating the DOM, because every time you read back a style that has been invalidated by a previous write call, you force a synchronous reflow.

Security warnings and errors

Security warnings and errors look like this:

The security messages shown in the Web Console help developers find potential or actual vulnerabilities in their sites. Additionally, many of these messages help educate developers because they end with a “Learn More” link that takes you to a page with background information and advice for mitigating the issue.

The complete list of security messages is as follows:

Message Details
Blocked loading mixed active content The page contained mixed active content: that is, the main page was served over HTTPS, but asked the browser to load "active content", such as scripts, over HTTP. The browser blocked this active content. See Mixed Content for more details.
Blocked loading mixed display content The page contained mixed display content: that is, the main page was served over HTTPS, but asked the browser to load "display content", such as images, over HTTP. The browser blocked this display content. See Mixed Content for more details.
Loading mixed (insecure) active content on a secure page The page contained mixed active content: that is, the main page was served over HTTPS, but asked the browser to load "active content", such as scripts, over HTTP. The browser loaded this active content. See Mixed Content for more details.
Loading mixed (insecure) display content on a secure page The page contained mixed display content: that is, the main page was served over HTTPS, but asked the browser to load "display content", such as images, over HTTP. The browser loaded this display content. See Mixed Content for more details.
This site specified both an X-Content-Security-Policy/Report-Only header and a Content-Security-Policy/Report-Only header. The X-Content-Security-Policy/Report-Only header(s) will be ignored. See Content Security Policy for more details.
The X-Content-Security-Policy and X-Content-Security-Report-Only headers will be deprecated in the future. Please use the Content-Security-Policy and Content-Security-Report-Only headers with CSP spec compliant syntax instead. See Content Security Policy for more details.
Password fields present on an insecure (http://) page. This is a security risk that allows user login credentials to be stolen. Pages containing login forms must be served over HTTPS, not HTTP.
Password fields present in a form with an insecure (http://) form action. This is a security risk that allows user login credentials to be stolen. Forms containing password fields must submit them over HTTPS, not HTTP.
Password fields present on an insecure (http://) iframe. This is a security risk that allows user login credentials to be stolen. iframes containing login forms must be served over HTTPS, not HTTP.
The site specified an invalid Strict-Transport-Security header. See HTTP Strict Transport Security for more details.

New in Firefox 36

This site makes use of a SHA-1 Certificate; it's recommended you use certificates with signature algorithms that use hash functions stronger than SHA-1.

The site uses a certificate whose signature uses the SHA-1 hash algorithm.

SHA-1 is still still widely used in certificates, but it is starting to show its age. Web sites and Certification Authorities are encouraged to switch to stronger hash algorithms in future. See the Weak Signature Algorithm article for more details.

Note that the SHA-1 certificate may not be your site's own certificate, but may be the certificate belonging to a Certification Authority that was used to sign your site's certificate.

Bug 863874 is the meta-bug for logging relevant security messages to the Web Console. If you have more ideas for useful features like the ones discussed here, or are interested in contributing, check out the metabug and its dependencies.

console API messages


This section describes the Web Console output for those console API calls that actually result in output. For more general documentation on the console API, please refer to its documentation page.

From Firefox 40 onwards, the Web Console can display console messages from Shared Workers, Service Workers, and Chrome Workers. Check the relevant options in the Filtering dropdown menu to see them.

Error messages

API Message content
error()

The argument to error().

console.error("an error");

The console will display a full stack trace for errors:

function error() {
  console.error("an error");
}

function call_error() {
  error();
}

call_error();

exception() An alias for error().
assert()

If the assertion succeeds, nothing. If the assertion fails, the argument:

console.assert(false, "My assertion always fails");

The console will display a full stack trace for assertions:

function assertion() {
  console.assert(false, "assertion failed");
}

function call_assertion() {
  assertion();
}

call_assertion();

Warning messages

API Message content
warn()

The argument to warn().

console.warn("a warning");

Info messages

API Message content
info()

The argument to info().

console.info("some info");

Log messages

API Message content
count()

The label supplied, if any, and the number of times this occurrence of count() has been called with the given label:

console.count(user.value);

dir()

Listing of the object's properties:

var user = document.getElementById('user');
console.dir(user);
dirxml() Aliased to log().
log()

The argument to log().

console.log("logged");

 

If the argument is a DOM node, the console gives you rich inspectable output for it:

table()

Display tabular data as a table.

time()

Notification that the specified timer started.

console.time("t");
timeEnd()

Duration for the specified timer.

console.timeEnd("t");
trace()

Stack trace:

console.trace();

Grouping messages

You can use console.group() to create indented groups in the console output. See Using groups in the console for more information on this.

Styling messages

Starting in Firefox 31, you can use the "%c" format specifier to style console messages:

console.log("%cMy stylish message", "color: red; font-style: italic");

Input/output messages

Commands sent to the browser using the Web Console's command line, and the corresponding responses, are logged using lines like this:

The dark gray bar indicates that these are input/output messages, while the direction of the arrow discriminates between input and output.

Filtering and searching

Filtering by type

You can use the toolbar along the top to constrain the results displayed.

To see only messages of particular types, click the button labeled with that type ("Net", "CSS", and so on). Clicking the main part of the button toggles that type on or off, while clicking the arrow on the right gives you more fine-grained filter options within that type (for example, whether to display errors and warnings).

From Firefox 40 onwards, you can adjust the "Logging" filter options so as to see messages from workers and add-ons:

Filtering by text

To see only messages that contain a specific string, type in the text box labeled "Filter output".

Clearing the log

Finally, you can use this toolbar to clear the log.

The command line interpreter

You can interpret JavaScript expressions in real time using the command line provided by the Web Console.

Entering expressions

To enter expressions just type into the command line and press Enter. To enter multiline expressions, use ShiftEnter instead of Enter.

The expression you type is echoed in the message display window, followed by the result:

Accessing variables

You can access variables defined in the page, both built-in variables like window and variables added by JavaScript like jQuery:

Autocomplete

The command line has autocomplete: enter the first few letters and a popup appears with possible completions:

Type Enter or Tab to accept the suggestion, use the up/down arrows to move to a different suggestion, or just keep typing if you don't like any of the suggestions.

The console suggests completions from the scope of the currently executing stack frame. This means that if you've hit a breakpoint in a function you get autocomplete for objects local to the function.

You get autocomplete suggestions for array elements, as well:

Defining variables

You can define your own variables, and then access them:

Command history

The command line remembers commands you've typed: to move back and forward through your history, use the up and down arrows.

From Firefox 39 onwards, this history is persisted across sessions. To clear the history, use the clearHistory() helper function.

Working with iframes

If a page contains embedded iframes, you can use the cd() command to change the console's scope to a specific iframe, and then you can execute functions defined in the document hosted by that iframe. There are three ways to select an iframe using cd():

You can pass the iframe DOM element:

var frame = document.getElementById("frame1");
cd(frame);

You can pass a CSS selector that matches the iframe:

cd("#frame1");

You can pass the iframe's global window object:

var frame = document.getElementById("frame1");
cd(frame.contentWindow);

To switch the context back to the top-level window, call cd() with no arguments:

cd();

For example, suppose we have a document that embeds an iframe:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
  </head>
  <body>
    <iframe id="frame1" src="static/frame/my-frame1.html"></iframe>
  </body>
</html>

The iframe defines a new function:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="UTF-8">
    <script>
      function whoAreYou() {
        return "I'm frame1";
      }
   </script>
  </head>
  <body>
  </body>
</html>

You can switch context to the iframe like this:

cd("#frame1");

Now you'll see that the global window's document is the iframe:

And you can call the function defined in the iframe:

Helper commands

The JavaScript command line provided by the Web Console offers a few built-in helper functions that make certain tasks easier.

$()
Looks up a CSS selector string, returning the first element that matches. Equivalent to document.querySelector() or calls the $ function in the page, if it exists.
$$()
Looks up a CSS selector string, returning a list of DOM nodes that match. This is a shortcut for document.querySelectorAll().

From Firefox 41, this method is no longer a shortcut for document.querySelectorAll() and instead returns an array of elements.
$0
The currently-inspected element in the page.
$_
New in Firefox 39. Stores the result of the last expression executed in the console's command line. For example, if you type "2+2 <enter>", then "$_ <enter>", the console will print 4.
$x()
Evaluates an XPath expression and returns an array of matching nodes.
keys()
Given an object, returns a list of the keys (or property names) on that object. This is a shortcut for Object.keys.
values()
Given an object, returns a list of the values on that object; serves as a companion to keys().
clear()
Clears the console output area.
inspect()
Given an object, opens the object inspector for that object.
pprint()
Formats the specified value in a readable way; this is useful for dumping the contents of objects and arrays.
help()
Displays help text. Actually, in a delightful example of recursion, it will bring you to this page.
cd()
Switch JavaScript evaluation context to a different iframe in the page. See working with iframes.
copy()
New in Firefox 38. Copy the argument to the clipboard. If the argument is a string, it's copied as-is. If the argument is a DOM node, its outerHTML is copied. Otherwise, JSON.stringify will be called on the argument, and the result will be copied to the clipboard.
clearHistory()
New in Firefox 39. Just like a normal command line, the console command line remembers the commands you've typed. Use this function to clear the console's command history.
Please refer to the Console API for more information about logging from content.

Rich output for objects

When the Web console prints objects, it includes a richer set of information than just the object's name. In particular, it:

Type-specific rich output

The Web Console provides rich output for many object types, including the following:

Object
Array
Date
Promise

New in Firefox 36

RegExp
Window
Document
Element

Examining object properties

When an object is logged to the console it appears in italics. Click on it, and you'll see a new panel appear containing details of the object:

To dismiss this panel press Esc..

Highlighting and inspecting DOM nodes

If you hover the mouse over any DOM element in the console output, it's highlighted in the page:

In the screenshot above you'll also see a blue "target" icon next to the node in the console output: click it to switch to the Inspector with that node selected.

The split console

You can use the console alongside other tools. While you're in another tool in the Toolbox, just press Esc or press the "Toggle split console" button in the Toolbar. The toolbox will now appear split, with the original tool above and the web console underneath.

As usual, $0 works as a shorthand for the element currently selected in the Inspector:

When you use the split console with the debugger, the console's scope is the currently executing stack frame. So if you hit a breakpoint in a function, the scope will be the function's scope. You'll get autocomplete for objects defined in the function, and can easily modify them on the fly:

Keyboard shortcuts

  Windows OS X Linux
Открыть веб-консоль Ctrl + Shift + K Cmd + Opt + K Ctrl + Shift + K
Искать в панели показа сообщений Ctrl + F Cmd + F Ctrl + F
Очистить панель инспектирования объекта Escape Escape Escape
Переместить фокус на командную строку Ctrl + Shift + K Cmd + Opt + K Ctrl + Shift + K

Интерпретатор командной строки

Эти клавиатурные сокращения работают, пока вы находитесь в интерпретаторе командной строки.

  Windows OS X Linux
Scroll to start of console output (new in Firefox 34, and only if the command line is empty) Home Home Home
Scroll to end of console output (new in Firefox 34, and only if the command line is empty) End End End
Прокрутить вверх вывод консоли Page up Page up Page up
Прокрутить вниз вывод консоли Page down Page down Page down
Переместиться назад по истории команд Up arrow Up arrow Up arrow
Переместиться вперёд по истории команд Down arrow Down arrow Down arrow
Перейти в начало строки Home Ctrl + A Ctrl + A
Перейти в конец строки End Ctrl + E Ctrl + E
Выполнить текущее выражение Enter Enter Enter
Добавить новую строку, чтобы войти в режим ввода многострочного выражения Shift + Enter Shift + Enter Shift + Enter

Всплывающее окно автодополнения

Эти клавиатурные сокращения работают, когда открыто всплывающее окно автодополнения:

  Windows OS X Linux
Выбрать текущее предложение в окне автодополнения Tab Tab Tab
Закрыть окно автодополнения Escape Escape Escape
Перейти к предыдущему предложению в окне автодополнения вверх вверх вверх
Перейти к следующему предложению в окне автодополнения вниз вниз вниз
Прокрутить вверх предложения в окне автодополнения Page up Page up Page up
Прокрутить вниз предложения в окне автодополнения Page down Page down Page down
Scroll to start of autocomplete suggestions (new in Firefox 34) Home Home Home
Scroll to end of autocomplete suggestions (new in Firefox 34) End End End

Global shortcuts

Эти сокращения работают для всех инструментов, находящихся в окне набора инструментов.

  Windows OS X Linux
Увеличить размер шрифта Ctrl + + Cmd + + Ctrl + +
Уменьшить размер шрифта Ctrl + - Cmd + - Ctrl + -
Сбросить размер шрифта Ctrl + 0 Cmd + 0 Ctrl + 0

Метки документа и участники

Contributors to this page: kirillivan0ff, uleming, Aleksej, bassam, Sheppy
Обновлялась последний раз: kirillivan0ff,