The JavaScript input interpreter - Firefox Developer Tools 编辑

You can interpret JavaScript expressions in real time using the interpreter provided by the Web Console. It has two modes: single-line entry and multi-line entry.

Single-line mode

For single-line entry, you can type JavaScript expressions in the field at the bottom of the console log, at the >> prompt.

The Web Console, showing single-line mode

To enter expressions in single-line mode, type at the prompt and press Enter. To enter multi-line expressions, press Shift+Enter after typing each line, then Enter to run all the entered lines.

The expression you type is echoed under the input prompt, followed by the result.

If your input does not appear to be complete when you press Enter, then the Console treats this as Shift+Enter , enabling you to finish your input.

For example, if you type:

function foo() {

and then Enter, the Console does not immediately execute the input, but behaves as if you had pressed Shift+Enter , so you can finish entering the function definition.

Multi-line mode

For multi-line entry, click the "split panel" icon at the right hand side of the single-line entry field, or press  Ctrl+B (Windows/Linux) or Cmd+B (macOS). The multi-line editing pane opens on the left side the of Web Console.

Web Console in multi-line mode

You can enter multiple lines of JavaScript by default in this mode, pressing Enter after each one. To execute the snippet that is currently in the editing pane, click the Run button or press Ctrl+Enter (or Cmd+Return on MacOS). The snippet is echoed under the input prompt (in the right-side pane), followed by the result. You can also select a range of lines in the editing pane, and run just the code on those lines.

Starting in Firefox 76, if the code snippet is more than five lines long, only the first five lines are echoed in the console, preceded by a disclosure triangle (or "twistie"), and followed by an ellipsis (…). Click anywhere in the area containing the echoed code to show the whole snippet; click again in that area to collapse it.

You can open files when in multi-line mode, and save the current contents of the editing pane to a file.

  • To open a file, press Ctrl+O (Cmd+O on MacOS). A file dialog box opens so you can select the file to open.
  • To save the contents of the editing pane, press Ctrl+S (Cmd+S on MacOS). A file dialog box opens so you can specify the location to save to.

To switch back to single-line mode, click the X icon at the top of the multi-line editing pane, or press  Ctrl+B (Windows/Linux) or Cmd+B (MacOS).

Accessing variables

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

Autocomplete

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

Press  Enter, Tab, or the right arrow key 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.

Console autocomplete suggestions are case-insensitive.

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:

You can enable or disable autocompletion via the Settings ("gear") menu in the Web Console toolbar. The menuitem Enable Autocompletion has a checkmark next to it when the feature is enabled, which is missing when it is disabled. Select the menuitem to change the state.

Instant evaluation

This feature is available in Firefox Nightly, in versions labeled 74 and later.

When the "instant evaluation" feature is enabled, the interpreter displays results of expressions as you're typing them in single-line mode. Note that the result might be an error message. Expressions that have side effects are not evaluated.

You can enable or disable instant evaluation via the Settings ("gear") menu in the Web Console toolbar. The menuitem Instant Evaluation has a checkmark next to it when the feature is enabled, which is missing when it is disabled. Select the menuitem to change the state.

Execution context

Code that you have executed becomes part of the execution context, regardless of what editing mode you were in when you executed it. For example, if you type a function definition in the multi-line editor, and click Run, you can switch to single-line mode and still use your function.

Syntax highlighting

Console output showing syntax highlighting

The text you enter has syntax highlighting as soon as you have typed enough for the highlighter to parse it and infer the meanings of the "words".

The output is highlighted as well where appropriate.

Note: Syntax highlighting is not visible in your browser if Accessibility features have been enabled.

Execution history

The interpreter remembers expressions you've typed. To move back and forward through your history:

  • In single-line mode, use the up and down arrows. 
  • In multi-line mode, use the  and icons in the editing panel's toolbar.

The expression history is persisted across sessions. To clear the history, use the clearHistory() helper function.

You can initiate a reverse search through the expression history, much like you can in bash on Linux and Mac or PowerShell on Windows. On Windows and Linux press F9. On Mac press Ctrl+R (note: not Cmd+R!) to initiate the reverse search.

Enter the text you want to search for in the input box at the bottom of the Console. Start typing part of the expression you are looking for and the first match is displayed in the console. Repeatedly typing F9 on Windows and Linux ( Ctrl+R on Mac) cycles backwards through the matches.

Once you  have initiated the reverse search, you can use Shift + F9 on Windows or Linux ( Ctrl+S on Mac) to search forward in the list of matches. You can also use the  and icons in the expression search bar.

When you find the expression you want, press Enter (Return) to execute the statement.

Working with iframes

Deprecated since Firefox 74 (bug 1605327); see Working with iframes for the newer, more-reliable technique. (cd() apparently never worked well cross-origin.)

If a page contains embedded iframes, you can use the cd() function 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.

$(selector, element)

Looks up a CSS selector string selector , returning the first node descended from element that matches. If unspecified, element defaults to document. Equivalent to document.querySelector() or calls the $ function in the page, if it exists.

See the QuerySelector code snippet.

$$(selector, element)
Looks up a CSS selector string selector, returning an array of DOM nodes descended from element that match. If unspecified, element defaults to document. This is like for document.querySelectorAll(), but returns an array instead of a NodeList.
$0
The currently-inspected element in the page.
$_
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(xpath, element, resultType)
Evaluates the XPath xpath expression in the context of element and returns an array of matching nodes. If unspecified, element defaults to document. The resultType parameter specifies the type of result to return; it can be an XPathResult constant, or a corresponding string: "number", "string", "bool", "node", or "nodes"; if not provided, ANY_TYPE is used.
:block
(Starting in Firefox 80) Followed by an unquoted string, blocks requests where the URL contains that string. In the Network Monitor, the string now appears and is selected in the Request Blocking sidebar.  Unblock with :unblock.
cd() Deprecated since Gecko 74

Switches JavaScript evaluation context to a different iframe in the page. This helper accepts multiple different ways of identifying the frame to switch to. You can supply any of the following:

  • a selector string to be passed to document.querySelector to locate the iframe element
  • the iframe element itself
  • the content window inside the iframe

See working with iframes.

clear()
Clears the console output area.
clearHistory()
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.
copy()
Copies 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.
help()Deprecated since Gecko 62
:help
Displays help text. Actually, in a delightful example of recursion, it brings you to this page.
inspect()
Given an object, generates rich output for that object. Once you select the object in the output area, you can use the arrow keys to navigate the object.
keys()
Given an object, returns a list of the keys (or property names) on that object. This is a shortcut for Object.keys.
pprint() Obsolete since Gecko 74
Formats the specified value in a readable way; this is useful for dumping the contents of objects and arrays.
:screenshot
Creates a screenshot of the current page with the supplied filename. If you don't supply a filename, the image file will be named with the following format:

Screen Shot yyy-mm-dd at hh.mm.ss.png

The command has the following optional parameters:
CommandTypeDescription
--clipboardbooleanWhen present, this parameter will cause the screenshot to be copied to the clipboard.
--delaynumberThe number of seconds to delay before taking the screenshot.
--dprnumberThe device pixel ratio to use when taking the screenshot.
--filebooleanWhen present, the screenshot will be saved to a file, even if other options (e.g. --clipboard) are included.
--filenamestringThe name to use in saving the file. The file should have a ".png" extension.
--fullpagebooleanIf included, the full webpage will be saved. With this parameter, even the parts of the webpage which are outside the current bounds of the window will be included in the screenshot. When used, "-fullpage" will be appended to the file name.
--selectorstringThe CSS query selector for a single element on the page. When supplied, only this element will be included in the screenshot.
:unblock
(Starting in Firefox 80) Followed by an unquoted string, removes blocking for URLs containing that string. In the Network Monitor, the string is removed from the Request Blocking sidebar. No error is given if the string was not previously blocked.
values()
Given an object, returns a list of the values on that object; serves as a companion to keys().

Please refer to the Console API for more information about logging from content.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。
列表为空,暂无数据

词条统计

浏览:121 次

字数:20980

最后编辑:6 年前

编辑次数:0 次

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文