aboutsummaryrefslogtreecommitdiff
path: root/files/ru/tools/browser_console/index.html
blob: 00d49816ffea8828bf69931ecd50609cbef26810 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
---
title: Консоль браузера
slug: Tools/Browser_Console
tags:
  - Tools
  - Web Development
  - Браузер
  - Отладка
  - веб-разработка:инструменты
  - консоль
translation_of: Tools/Browser_Console
original_slug: Tools/Консоль_браузера
---
<div>{{ToolsSidebar}}</div><p>Консоль браузера — как <a href="/ru/docs/Tools/Web_Console" title="/ru/docs/Tools/Web_Console">Веб-консоль</a>, но для работы со всем браузером, а не с отдельной его вкладкой.</p>

<p>То есть, она протоколирует такую же информацию, что и Веб-консоль: сетевые запросы, ошибки и предупреждения JavaScript и CSS, ошибки и предупреждения о безопасности, и информационные сообщения, выдаваемые непосредственно кодом JavaScript. Однако она протоколирует эту информацию не только для одной вкладки с контентом, но для всех вкладок с контентом, для дополнений, и для кода самого браузера.</p>

<p>Если вы хотите использовать и другие инструменты, доступные в обычном <a href="/ru/docs/Tools/Tools_Toolbox">наборе инструментов веб-разработки</a>, с кодом дополнений или браузера, вам может пригодиться <a href="/ru/docs/Tools/Browser_Toolbox">Панель инструментов браузера</a>.</p>

<p>В Консоли браузера можно также выполнять и выражения JavaScript. 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 <a href="/ru/docs/Code_snippets/Tabbed_browser" title="/ru/docs/Code_snippets/Tabbed_browser"><code>gBrowser</code></a> global, and even with the XUL used to specify the browser's user interface.</p>

<div class="geckoVersionNote">
<p>Внимание: начиная с Firefox 30, командная строка Консоли браузера (куда вставляются выражения JavaScript) по умолчанию выключена. Чтобы её включить, присвойте настройке about:config <code>devtools.chrome.enabled</code> значение <code>true</code>, либо поставьте галочку «Включить инструменты отладки browser chrome и дополнений» (начиная с Firefox 40) / «Включить отладку chrome и дополнений» (по Firefox 38.0.5 включительно) в <a href="/ru/docs/Tools_Toolbox#Advanced_settings">настройках панели инструментов разработчика</a>.</p>
</div>

<h2 id="Открытие_Консоли_браузера">Открытие Консоли браузера</h2>

<p>Консоль браузера можно открыть двумя способами:</p>

<ol>
 <li>из меню: выбрать «Консоль браузера» из меню Разработка в меню Firefox (или меню Инструменты, если оно включено или на OS X)</li>
 <li>с клавиатуры: нажать Ctrl+Shift+J (или Cmd+Shift+J на Mac).</li>
</ol>

<p>Note that until Firefox 38, if the Browser Console has become hidden by a normal Firefox window and you select it again, either from the menu or from the keyboard, then it will be closed. From Firefox 38 onwards, this instead has the effect of switching the focus back to the Browser Console, which is more likely to be what you wanted.</p>

<p>You can also start the Browser Console by launching Firefox from the command line and passing the <code>-jsconsole</code> argument:</p>

<pre>/Applications/FirefoxAurora.app/Contents/MacOS/firefox-bin -jsconsole</pre>

<p>The Browser Console looks like this:</p>

<p><img alt="" src="https://mdn.mozillademos.org/files/5847/browser-console-window.png" style="display: block; margin-left: auto; margin-right: auto;"></p>

<p>You can see that the Browser Console looks and behaves very much like the <a href="/en-US/docs/Tools/Web_Console" title="/en-US/docs/Tools/Web_Console">Web Console</a>:</p>

<ul>
 <li>most of the window is occupied by a <a href="/en-US/docs/Tools/Web_Console#Message_Display_Pane" title="/en-US/docs/Tools/Web_Console#Message_Display_Pane">pane that display messages</a></li>
 <li>at the top, a <a href="/en-US/docs/Tools/Web_Console#Filtering_and_searching" title="/en-US/docs/docs/Tools/Web_Console#Filtering_and_searching">toolbar</a> enables you to filter the messages that appear</li>
 <li>at the bottom, a <a href="/en-US/docs/Tools/Web_Console#The_command_line_interpreter" title="/en-US/docs/docs/Tools/Web_Console#The_command_line_interpreter">command line interpreter</a> enables you to evaluate JavaScript expressions.</li>
</ul>

<h2 id="Browser_Console_logging">Browser Console logging</h2>

<p>The Browser console logs the same sorts of messages as the Web Console:</p>

<ul>
 <li><a href="/en-US/docs/Tools/Web_Console#HTTP_requests" title="/en-US/docs/Tools/Web_Console#HTTP_requests">HTTP requests</a></li>
 <li><a href="/en-US/docs/Tools/Web_Console#Warnings_and_errors" title="/en-US/docs/Tools/Web_Console#Warnings_and_errors">Warnings and errors</a> (including JavaScript, CSS, security warnings and errors, and messages explicitly logged by JavaScript code using the <a href="https://developer.mozilla.org/en-US/docs/Web/API/console" title="/en-US/docs/Web/API/console">console</a> API)</li>
 <li><a href="/en-US/docs/Tools/Web_Console#Input.2Foutput_messages" title="/en-US/docs/Tools/Web_Console#Input.2Foutput_messages">Input/output messages</a>: commands send to the browser via the command line, and the result of executing them.</li>
</ul>

<p>However, it displays such messages from:</p>

<ul>
 <li>web content hosted by all browser tabs</li>
 <li>the browser's own code</li>
 <li>add-ons.</li>
</ul>

<h3 id="Messages_from_add-ons">Messages from add-ons</h3>

<p>The Browser Console displays messages logged by all Firefox add-ons.</p>

<h4 id="Console.jsm">Console.jsm</h4>

<p>To use the console API from a traditional or bootstrapped add-on, get it from the Console module.</p>

<p>One exported symbol from Console.jsm is "console". Below is an example of how to acess it, which adds a message to the Browser Console.</p>

<pre class="brush: js">Components.utils.import("resource://gre/modules/devtools/Console.jsm");
console.log("Hello from Firefox code"); //output messages to the console</pre>

<p>Learn more:</p>

<ul>
 <li><a href="/en-US/docs/Web/API/console">console API reference</a></li>
 <li><a href="http://mxr.mozilla.org/mozilla-release/source/toolkit/devtools/Console.jsm">Console.jsm source code in the <span style="line-height: 1.5;">Mozilla Cross-Reference</span></a></li>
</ul>

<h4 id="HUDService">HUDService</h4>

<p>There is also the HUDService which allows access to the Browse Console. The module is available at <a href="http://mxr.mozilla.org/mozilla-release/source/browser/devtools/webconsole/hudservice.js">Mozilla Cross-Reference</a>. We see we can not only access the Browser Console but also Web Console.</p>

<p>Here is an example on how to clear the contents of the Browser console:</p>

<pre class="brush: js">Components.utils.import("resource://gre/modules/devtools/Loader.jsm");
var HUDService = devtools.require("devtools/webconsole/hudservice");

var hud = HUDService.getBrowserConsole();
hud.jsterm.clearOutput(true);</pre>

<p>If you would like to access the content document of the Browser Console this can be done with the HUDService. This example here makes it so that when you mouse over the "Clear" button it will clear the Browser Console:</p>

<pre class="brush: js">Components.utils.import("resource://gre/modules/devtools/Loader.jsm");
var HUDService = devtools.require("devtools/webconsole/hudservice");

var hud = HUDService.getBrowserConsole();

var clearBtn = hud.chromeWindow.document.querySelector('.webconsole-clear-console-button');
clearBtn.addEventListener('mouseover', function() {
  hud.jsterm.clearOutput(true);
}, false);</pre>

<h4 id="Bonus_Features_Available">Bonus Features Available</h4>

<p>For <a href="https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/index.html" title="https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/index.html">Add-on SDK</a> add-ons, the console API is available automatically. Here's an example add-on that just logs an error when the user clicks a widget:</p>

<pre class="brush: js">widget = require("sdk/widget").Widget({
  id: "an-error-happened",
  label: "Error!",
  width: 40,
  content: "Error!",
  onClick: logError
});

function logError() {
  console.error("something went wrong!");
}</pre>

<p>If you <a href="https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/tutorials/installation.html" title="https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/tutorials/installation.html">build this as an XPI file</a>, then open the Browser Console, then open the XPI file in Firefox and install it, you'll see a widget labeled "Error!" in the Add-on bar:</p>

<p><img alt="" src="https://mdn.mozillademos.org/files/5937/browser-console-addon.png" style="display: block; margin-left: auto; margin-right: auto;">Click the icon. You'll see output like this in the Browser Console:</p>

<p><img alt="" src="https://mdn.mozillademos.org/files/5851/browser-console-addon-output.png" style="display: block; margin-left: auto; margin-right: auto;"></p>

<p>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 <a href="/en-US/docs/Tools/Web_Console#Filtering_and_searching" title="/en-US/docs/Tools/Web_Console#Filtering_and_searching">"Filter output"</a> search box. By default, only error messages are logged to the console, although <a href="https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/console.html#Logging%20Levels" title="https://addons.mozilla.org/en-US/developers/docs/sdk/latest/dev-guide/console.html#Logging%20Levels">you can change this in the browser's preferences</a>.</p>

<h2 id="Browser_Console_command_line">Browser Console command line</h2>

<div class="geckoVersionNote">
<p>From Firefox 30, the Browser Console command line is disabled by default. To enable it set the <code>devtools.chrome.enabled</code> preference to <code>true</code> in about:config, or set the "Enable chrome debugging" option in the <a href="/en-US/docs/Tools_Toolbox#Advanced_settings">developer tool settings</a>.</p>
</div>

<p>Like the Web Console, the command line interpreter enables you to evaluate JavaScript expressions in real time:<img alt="" src="https://mdn.mozillademos.org/files/5855/browser-console-commandline.png" style="display: block; margin-left: auto; margin-right: auto;">Also like the Web Console's command line interpreter, this command line supports <a href="/en-US/docs/Tools/Web_Console#Autocomplete" title="/en-US/docs/Tools/Web_Console#Autocomplete">autocomplete</a>, <a href="/en-US/docs/Tools/Web_Console#Command_history" title="/en-US/docs/Tools/Web_Console#Command_history">history</a>, and various <a href="/en-US/docs/Tools/Web_Console#Keyboard_shortcuts" title="/en-US/docs/docs/Tools/Web_Console#Keyboard_shortcuts">keyboard shortcuts </a>and <a href="/en-US/docs/Tools/Web_Console#Helper_commands" title="/en-US/docs/Tools/Web_Console#Helper_commands">helper commands</a>. If the result of a command is an object, you can <a href="/en-US/docs/Tools/Web_Console#Inspecting_objects" title="/en-US/docs/Tools/Web_Console#Inspecting_objects">click on the object to see its details</a>.</p>

<p>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 <code>window</code>:</p>

<p><img alt="" src="https://mdn.mozillademos.org/files/5867/browser-console-chromewindow.png" style="display: block; margin-left: auto; margin-right: auto;"></p>

<p>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.</p>

<h3 id="Controlling_the_browser">Controlling the browser</h3>

<p>The command line interpreter gets access to the <a href="/en-US/docs/XUL/tabbrowser" title="/en-US/docs/XUL/tabbrowser"><code>tabbrowser</code></a> object, through the <code>gBrowser</code> 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):</p>

<pre class="brush: js">var newTabBrowser = gBrowser.getBrowserForTab(gBrowser.selectedTab);
newTabBrowser.addEventListener("load", function() {
  newTabBrowser.contentDocument.body.innerHTML = "&lt;h1&gt;this page has been eaten&lt;/h1&gt;";
}, true);
newTabBrowser.contentDocument.location.href = "https://mozilla.org/";</pre>

<p>It adds a listener to the currently selected tab's <code>load</code> event that will eat the new page, then loads a new page.</p>

<h3 id="Modifying_the_browser_UI">Modifying the browser UI</h3>

<p>Since the global <code>window</code> 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:</p>

<pre class="brush: js">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);</pre>

<p><img alt="" src="https://mdn.mozillademos.org/files/5859/browser-console-modify-ui-windows.png" style="display: block; margin-left: auto; margin-right: auto;">On OS X, this similar code will add a new item to the "Tools" menu:</p>

<pre class="brush: js">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);</pre>

<p><img alt="" src="https://mdn.mozillademos.org/files/5861/browser-console-modify-ui-osx.png" style="display: block; margin-left: auto; margin-right: auto;"></p>