Mozilla

Firefox Articles

Sort by:

View:

  1. Network Monitor, now in Firefox Beta

    The Firefox Developer Tools team is particularly proud announce that Firefox 23 (in Firefox Beta, to be released today) ships with an initial but very functional Network Monitor tool that not only provides similar functionality to other tool sets, but in many improves on them. This important step is the result of lots of hard work from the entire team, but in particular Victor Porof and Mihai Sucan.

    Let’s get started

    To give you the best idea of how the network monitor works, here’s a series of steps to follow:

    1. Download, install and run Firefox 23 beta if you haven’t already (or Firefox Aurora or Firefox Nightly – more on Firefox and the release channels).
    2. Open the Network Monitor tool:
      • from the menu: Tools => Web Developer => Network
      • from the keyboard: Ctrl + Alt + Q (Windows/Linux) or Cmd + Alt + Q (Mac OS X)
    3. Load an interesting site.

    As Firefox loads the page you’ll see each individual request get added as a row, much as you would expect from other tools. In particular it is now very easy to visualize not just how quickly parts of the page load and in what order, but also where problems are: missing assets, slow web servers, buggy apis.

    As you get used to using the Network Monitor, you’ll also notice that you don’t need to necessarily hit refresh on a page that is already loaded, once you open the network tool any subsequent requests that happen will be logged. For example, if you’re interested in xhr requests made by an app, just open the monitor and start clicking buttons – you should see any api calls logged as normal without needing to reload.

    Status at a glance

    One thing you should notice right away about the way the Network tool displays a page load is that we’ve taken care to provide both information and design cues to show you what is happening at a glance as the page loads:

    We’ve tried to create a clean UI that delivers key aspects of how an entire page loads without creating too much visual clutter:

    • An error such as a 404 are colored dark red to make them stand out visually from the green successful or yellow cached requests.
    • The url is parsed out and only the file name and domain are shown.
    • By default the load is sorted in chronological order, but you can also sort by any of the top columns, for example by domain or filename.
    • You can easily see the type of request, whether it be html content, an image or an API request.
    • You can click on the column headers to sort requests by method, file name, domain, type or size.

    It’s all in the details

    Once all the page’s assets have been loaded, clicking on a single request opens up the sidebar view which provides detailed information about that request, broken down into panels that display different aspects of a given request: Headers, Cookies, Parameters, Response and Timings. Similar to how the Inspector tool works, this panel is responsive and will neatly pop down below the request list if you’ve docked the tools to the right side:

    A quick tour

    The Headers panel is particularly useful for debugging asset caching problems, and this panel provides parsed lists for both the request and response headers that also supports filtering based on either name or value:

    The Timings panel gives you a detailed, visual breakdown of where time was spent for the selected request. Is it DNS? Is it the server itself?

    If you’re debugging API requests or form posts, you’ll really like how we’ve parsed out the url parameters in the Params panel:

    Are you using a lot of API calls to improve the responsiveness of your app? JSON responses are parsed and displayed as a navigable object in the Response panel to make it easy to check on the data coming back from the server. You can filter the data based on JSON values as well.

    Next Steps

    It’s great to deliver the Network Monitor to a much wider set of developers in Firefox 23 Beta but we haven’t stopped adding new features in the meantime. Firefox 24 ( now in the Aurora channel ) features several notable improvements that have landed in the last 6 weeks or so:

    • You can now filter requests based on the request ‘type’, including XHR, images, html.
    • POST request parameters are supported in the Params panel.
    • You can browse the list of requests via the Up/Down arrow keys.
    • Many more bug fixes and refinements!
  2. Content Security Policy 1.0 lands in Firefox Aurora

    The information in this article is based on work together with Ian Melven, Kailas Patil and Tanvi Vyas.

    We have just landed support for the Content Security Policy (CSP) 1.0
    specification
    in Firefox Aurora (Firefox 23), available as of tomorrow (May 30th). CSP is a security mechanism that aims to protect a website against content injection attacks by providing a whitelist of known-good domain names to accept JavaScript (and other content) from. CSP does this by sending a Content-Security-Policy header with the document it protects (yes, we lost the X prefix with the 1.0 version of the spec).

    To effectively protect against XSS, a few JavaScript features have to be
    disabled:

    • All inline JavaScript is disallowed. This means, that all the JavaScript code must be placed in a separate file that is linked via <script src=... >
    • All calls to functions which allow JavaScript code being executed from strings (e.g., eval) are disabled

    CSP now more intuitive and consistent

    While Firefox has had support for CSP since its invention here at Mozilla, things have been changing a lot. The streamlined development of a specification within the W3C has made the concept more intuitive and consistent. Most directives in a CSP header are now of a unified form which explicitly specifies the type of content you want to restrict:

    • img-src
    • object-src
    • script-src
    • style-src and so on.

    Oh and if you feel like you must allow less secure JavaScript coding styles, you can add the values unsafe-inline or unsafe-eval to your list of script sources. (This used to be inline-script and eval-script before).

    Start protecting your website by implementing CSP now!

    But wait – isn’t that a bit tedious… Writing a complex policy and making sure that you remembered all the resources that your website requires? Don’t fret! Here comes UserCSP again!

    Generate your Content Security Policies with UserCSP!

    During the last few months, Kailas Patil, a student in our Security Mentorship Program has continued his GSoC work from last year to update UserCSP.

    UserCSP is a Firefox add-on that helps web developers and security-minded users use CSP. Web developers can create a Content Security Policy (CSP) for their site by using UserCSP’s infer CSP feature. This feature can list required resource URLs and turn them into a policy ready to plug into a CSP header.

    In addition, UserCSP is the first step to expose a policy enforcement mechanism directly to web users. Furthermore, users can enforce a stricter policy than a page supplies through the add-on or apply a policy to certain websites that don’t currently support CSP.

    While earlier versions of UserCSP were more aligned to content security policies as originally invented at Mozilla, this version is updated to be in compliance with the CSP 1.0 specification. This means that policies derived with this add-on may work in all browsers as soon as they support the specification. Hooray!

    As this evolves and ships, our MDN documentation on Content Security Policy (CSP) will keep on evolving, and we also plan to write more about this in the Mozilla Security Blog in the next few weeks, so stay tuned!

  3. Compiling to JavaScript, and Debugging with Source Maps

    Update 2013/05/29: I have updated the article to reflect recent changes in the source map specification where the //@ syntax for linking a source map to a script has been deprecated in favor of //# due to problems with Internet Explorer.

    This is a tutorial on how to write a compiler which generates JavaScript as its target language, and maintains line and column meta-data in source maps for debugging. Storing line and column coordinates in a source map allows the end-user of the compiler to debug the source code that they wrote, rather than the ugly, generated JavaScript they are not familiar with.

    In this tutorial, we will be compiling a small Reverse Polish Notation, or RPN, language to JavaScript. The language is super simple, and is nothing more than simple arithmetic with variable storage and output capabilities. We are keeping the language simple so that we can focus on integrating source maps with the compiler, rather than language implementation details.

    Availability

    Initial support for source maps in the debugger is available in Firefox 23 (Aurora at time of writing) with more improvements coming in Firefox 24 (Nightly at time of writing). Chrome DevTools also have support for source maps.

    Overview of the Source Language

    RPN uses postfix notation, meaning that the operator follows its two operands. One of the benefits of RPN is that as long as we limit ourselves to binary operators, we do not need any parentheses, and do not need to worry about operator precedence.

    Here is an example program in our source language:

    a 5 =;
    b 3 =;
    c a b + 4 * =;

    This is an equivalent program written in a language which uses infix notation for its arithmetic operators:

    a = 5;
    b = 3;
    c = (a + b) * 4;

    Our language will support addition, subtraction, multiplication, division, assignment, and printing. The print operator’s first operand is the value to print, the second operand is how many times to print the value and must be greater than or equal to one:

    5 1 print;
    # Output:
    # 5
     
    3 4 print;
    # Output:
    # 3
    # 3
    # 3
    # 3
     
    4 print;
    # Syntax error
     
    n -1 =;
    4 n print;
    # Runtime error

    Lastly, division by zero should throw an error:

    5 0 /;
    # Runtime error

    Getting Setup

    We will be writing our compiler on Node.js, using Jison to generate the parser for our language from a grammar, and using the source-map library to help generate source maps.

    The first step is to download and install Node.js if you don’t already have it on your system.

    After you have installed Node.js, use its package manager npm to create a new project for the compiler:

    $ mkdir rpn
    $ cd rpn/
    $ npm init .

    After the last command, npm will prompt you with a bunch of questions. Enter your name and email, answer ./lib/rpn.js for the main module/entry point, and just let npm use the defaults that it supplies for the rest of the questions.

    Once you have finished answering the prompts, create the directory layout for the project:

    $ mkdir lib
    $ touch lib/rpn.js
    $ mkdir -p lib/rpn

    The public API for the compiler will reside within lib/rpn.js, while the submodules we use to implement various things such as the lexer and abstract syntax tree will live in lib/rpn/*.js.

    Next, open up the package.json file and add jison and source-map to the project’s dependencies:

    ...
    "dependencies": {
      "jison": ">=0.4.4",
      "source-map": ">=0.1.22"
    },
    ...

    Now we will install a link to our package in Node.js’s globally installed packages directory. This allows us to import our package from the Node.js shell:

    $ npm link .

    Make sure that everything works by opening the Node.js shell and importing our package:

    $ node
    > require("rpn")
    {}

    Writing the Lexer

    A lexer (also known as a scanner or tokenizer) breaks the inputted raw source code into a stream of semantic tokens. For example in our case, we would want to break the raw input string "5 3 +;" into something like ["5", "3", "+", ";"].

    Because we are using Jison, rather than writing the lexer and parser by hand, our job is much easier. All that is required is to supply a list of rules that describe the types of tokens we are expecting. The left hand side of the rules are regular expressions to match individual tokens, the right hand side are the snippets of code to execute when an instance of the corresponding token type is found. These tokens will be passed on to the parser in the next phase of the compiler.

    Create the rules for lexical analysis in lib/rpn/lex.js:

    exports.lex = {
      rules: [
        ["\s+",                   "/* Skip whitespace! */"],
        ["#.*\n",                 "/* Skip comments! */"],
        [";",                      "return 'SEMICOLON'"],
        ["\-?[0-9]+(\.[0-9]+)?", "return 'NUMBER';"],
        ["print",                  "return 'PRINT';"],
        ["[a-zA-Z][a-zA-Z0-9_]*",  "return 'VARIABLE';"],
        ["=",                      "return '=';"],
        ["\+",                    "return '+';"],
        ["\-",                    "return '-';"],
        ["\*",                    "return '*';"],
        ["\/",                    "return '/';"],
        ["$",                      "return 'EOF';"]
      ]
    };

    Writing the Parser

    The parser takes the tokens from the lexer one at a time and confirms that the input is a valid program in our source language.

    Once again, the task of writing the parser is much easier than it would otherwise be thanks to Jison. Rather than writing the parser ourselves, Jison will programmatically create one for us if we provide a grammar for the language.

    If all we cared about was whether the input was a valid program, we would stop here. However, we are also going to compile the input to JavaScript, and to do that we need to create an abstract syntax tree. We build the AST in the code snippets next to each rule.

    A typical grammar contains productions with the form:

    LeftHandSide → RightHandSide1
                 | RightHandSide2
                 ...

    However, in Jison we are a) writing in JavaScript, and b) also providing code to execute for each rule so that we can create the AST. Therefore, we use the following format:

    LeftHandSide: [
      [RightHandSide1, CodeToExecute1],
      [RightHandSide2, CodeToExecute2],
      ...
    ]

    Inside the code snippets, there are a handful of magic variables we have access to:

    • $$: The value of the left hand side of the production.
    • $1/$2/$3/etc: The value of the the nth form in the right hand side of the production.
    • @1/@2/@3/etc: An object containing the line and column coordinates where the nth form in the right hand side of the production was parsed.
    • yytext: The full text of currently matched rule.

    Using this information, we can create the grammar in lib/rpn/bnf.js:

    exports.bnf = {
      start: [
        ["input EOF", "return $$;"]
      ],
      input: [
        ["",           "$$ = [];"],
        ["line input", "$$ = [$1].concat($2);"]
      ],
      line: [
        ["exp SEMICOLON", "$$ = $1;"]
      ],
      exp: [
        ["NUMBER",           "$$ = new yy.Number(@1.first_line, @1.first_column, yytext);"],
        ["VARIABLE",         "$$ = new yy.Variable(@1.first_line, @1.first_column, yytext);"],
        ["exp exp operator", "$$ = new yy.Expression(@3.first_line, @3.first_column, $1, $2, $3);"]
      ],
      operator: [
        ["PRINT", "$$ = new yy.Operator(@1.first_line, @1.first_column, yytext);"],
        ["=",     "$$ = new yy.Operator(@1.first_line, @1.first_column, yytext);"],
        ["+",     "$$ = new yy.Operator(@1.first_line, @1.first_column, yytext);"],
        ["-",     "$$ = new yy.Operator(@1.first_line, @1.first_column, yytext);"],
        ["*",     "$$ = new yy.Operator(@1.first_line, @1.first_column, yytext);"],
        ["/",     "$$ = new yy.Operator(@1.first_line, @1.first_column, yytext);"]
      ]
    };

    Implementing the Abstract Syntax Tree

    Create the definitions for the abstract syntax tree nodes in lib/rpn/ast.js.

    Since we will be maintaining line and column information in all of the AST nodes, we can reuse some code by making a base prototype:

    var AstNode = function (line, column) {
      this._line = line;
      this._column = column;
    };

    The definitions for the rest of the AST nodes are pretty straight forward. Link up the prototype chain, assign relevant attributes, and don’t forget to call AstNode‘s constructor:

    exports.Number = function (line, column, numberText) {
      AstNode.call(this, line, column);
      this._value = Number(numberText);
    };
    exports.Number.prototype = Object.create(AstNode.prototype);
     
    exports.Variable = function (line, column, variableText) {
      AstNode.call(this, line, column);
      this._name = variableText;
    };
    exports.Variable.prototype = Object.create(AstNode.prototype);
     
    exports.Expression = function (line, column, operand1, operand2, operator) {
      AstNode.call(this, line, column);
      this._left = operand1;
      this._right = operand2;
      this._operator = operator;
    };
    exports.Expression.prototype = Object.create(AstNode.prototype);
     
    exports.Operator = function (line, column, operatorText) {
      AstNode.call(this, line, column);
      this.symbol = operatorText;
    };
    exports.Operator.prototype = Object.create(AstNode.prototype);

    Compilation

    Generated JavaScript

    Before we generate JavaScript, we need a plan. There are a couple ways we can structure the outputted JavaScript.

    One strategy is to translate the RPN expressions to the equivalent human readable JavaScript expression we would create if we had been writing JavaScript all along. For example, if we were to port this RPN example:

    a 8 =;
    b 2 =;
    c a b 1 - / =;

    We might write the following JavaScript:

    var a = 8;
    var b = 3;
    var c = a / (b - 1);

    However, this means that we are completely adopting the nuances of JavaScript’s arithmetic. In an earlier example, we saw that a helpful runtime error was thrown when any number was divided by zero. Most languages throw an error when this occurs, however JavaScript does not; instead, the result is Infinity. Therefore, we can’t completely embrace JavaScript’s arithmetic system, and we must generate some code to check for divide-by-zero errors ourselves. Adding this code gets a little tricky if we want to maintain the strategy of generating human readable code.

    Another option is treating the JavaScript interpreter as a stack machine of sorts and generating code that pushes and pops values to and from a stack. Furthermore, stack machines are a natural fit for evaluating RPN. In fact, it is such a good fit that RPN “was independently reinvented by F. L. Bauer and E. W. Dijkstra in the early 1960s to reduce computer memory access and utilize the stack to evaluate expressions.”

    Generating JavaScript code for the same example above, but utilizing the JavaScript interpreter as a stack machine, might look something like this:

    push(8);
    push('a');
    env[pop()] = pop();
    push(2);
    push('b');
    env[pop()] = pop();
    push('a');
    push('b');
    push(1);
    temp = pop();
    push(pop() - temp);
    temp = pop();
    if (temp === 0) throw new Error("Divide by zero");
    push(pop() / temp);
    push('c');
    env[pop()] = pop();

    This is the strategy we will follow. The generated code is a bit larger, and we will require a preamble to define push, pop, etc, but compilation becomes much easier. Furthermore, the fact that the generated code isn’t as human readable only highlights the benefits of using source maps!

    Creating Source Maps

    If we weren’t generating source maps along with our generated JavaScript, we could build the generated code via concatenating strings of code:

    code += "push(" + operand1.compile() + " "
      + operator.compile() + " "
      + operand2.compile() + ");n";

    However, this doesn’t work when we are creating source maps because we need to maintain line and column information. When we concatenate strings of code, we lose that information.

    The source-map library contains SourceNode for exactly this reason. If we add a new method on our base AstNode prototype, we can rewrite our example like this:

    var SourceNode = require("source-map").SourceNode;
    AstNode.prototype._sn = function (originalFilename, chunk) {
      return new SourceNode(this._line, this._column, originalFilename, chunk);
    };
     
    ...
     
    code = this._sn("foo.rpn", [code,
                                "push(",
                                operand1.compile(), " ",
                                operator.compile(), " ",
                                operand2.compile(), ");n"]);

    Once we have completed building the SourceNode structure for the whole input program, we can generate the compiled source and the source map by calling the SourceNode.prototype.toStringWithSourceMap method. This method returns an object with two properties: code, which is a string containing the generated JavaScript source code; and map, which is the source map.

    Implementing Compilation

    Now that we have a strategy for generating code, and understand how to maintain line and column information so that we can generate source maps easily, we can add the methods to compile our AST nodes to lib/rpn/ast.js.

    To play nice with the global JavaScript environment, we will namespace push, pop, etc, under __rpn.

    function push(val) {
      return ["__rpn.push(", val, ");n"];
    }
     
    AstNode.prototype.compile = function (data) {
      throw new Error("Not Yet Implemented");
    };
    AstNode.prototype.compileReference = function (data) {
      return this.compile(data);
    };
    AstNode.prototype._sn = function (originalFilename, chunk) {
      return new SourceNode(this._line, this._column, originalFilename, chunk);
    };
     
    exports.Number.prototype.compile = function (data) {
      return this._sn(data.originalFilename,
                      push(this._value.toString()));
    };
     
    exports.Variable.prototype.compileReference = function (data) {
      return this._sn(data.originalFilename,
                      push(["'", this._name, "'"]));
    };
    exports.Variable.prototype.compile = function (data) {
      return this._sn(data.originalFilename,
                      push(["window.", this._name]));
    };
     
    exports.Expression.prototype.compile = function (data) {
      var temp = "__rpn.temp";
      var output = this._sn(data.originalFilename, "");
     
      switch (this._operator.symbol) {
      case 'print':
        return output
          .add(this._left.compile(data))
          .add(this._right.compile(data))
          .add([temp, " = __rpn.pop();n"])
          .add(["if (", temp, " <= 0) throw new Error('argument must be greater than 0');n"])
          .add(["if (Math.floor(", temp, ") != ", temp,
                ") throw new Error('argument must be an integer');n"])
          .add([this._operator.compile(data), "(__rpn.pop(), ", temp, ");n"]);
      case '=':
        return output
          .add(this._right.compile(data))
          .add(this._left.compileReference(data))
          .add(["window[__rpn.pop()] ", this._operator.compile(data), " __rpn.pop();n"]);
      case '/':
        return output
          .add(this._left.compile(data))
          .add(this._right.compile(data))
          .add([temp, " = __rpn.pop();n"])
          .add(["if (", temp, " === 0) throw new Error('divide by zero error');n"])
          .add(push(["__rpn.pop() ", this._operator.compile(data), " ", temp]));
      default:
        return output
          .add(this._left.compile(data))
          .add(this._right.compile(data))
          .add([temp, " = __rpn.pop();n"])
          .add(push(["__rpn.pop() ", this._operator.compile(data), " ", temp]));
      }
    };
     
    exports.Operator.prototype.compile = function (data) {
      if (this.symbol === "print") {
        return this._sn(data.originalFilename,
                        "__rpn.print");
      }
      else {
        return this._sn(data.originalFilename,
                        this.symbol);
      }
    };

    Gluing it Together

    From here we have done all the difficult work, and we can run a victory lap by connecting the modules together with a public API, and by creating a command line script to call the compiler.

    The public API resides in lib/rpn.js. It also contains the preamble, to initialize __rpn:

    var jison = require("jison");
    var sourceMap = require("source-map");
    var lex = require("./rpn/lex").lex;
    var bnf = require("./rpn/bnf").bnf;
     
    var parser = new jison.Parser({
      lex: lex,
      bnf: bnf
    });
     
    parser.yy = require("./rpn/ast");
     
    function getPreamble () {
      return new sourceMap.SourceNode(null, null, null, "")
        .add("var __rpn = {};n")
        .add("__rpn._stack = [];n")
        .add("__rpn.temp = 0;n")
     
        .add("__rpn.push = function (val) {n")
        .add("  __rpn._stack.push(val);n")
        .add("};n")
     
        .add("__rpn.pop = function () {n")
        .add("  if (__rpn._stack.length > 0) {n")
        .add("    return __rpn._stack.pop();n")
        .add("  }n")
        .add("  else {n")
        .add("    throw new Error('can\'t pop from empty stack');n")
        .add("  }n")
        .add("};n")
     
        .add("__rpn.print = function (val, repeat) {n")
        .add("  while (repeat-- > 0) {n")
        .add("    var el = document.createElement('div');n")
        .add("    var txt = document.createTextNode(val);n")
        .add("    el.appendChild(txt);n")
        .add("    document.body.appendChild(el);n")
        .add("  }n")
        .add("};n");
    }
     
    exports.compile = function (input, data) {
      var expressions = parser.parse(input.toString());
      var preamble = getPreamble();
     
      var result = new sourceMap.SourceNode(null, null, null, preamble);
      result.add(expressions.map(function (exp) {
        return exp.compile(data);
      }));
     
      return result;
    };

    Create the command line script in bin/rpn.js:

    #!/usr/bin/env node
    var fs = require("fs");
    var rpn = require("rpn");
     
    process.argv.slice(2).forEach(function (file) {
      var input = fs.readFileSync(file);
      var output = rpn.compile(input, {
        originalFilename: file
      }).toStringWithSourceMap({
        file: file.replace(/.[w]+$/, ".js.map")
      });
      var sourceMapFile = file.replace(/.[w]+$/, ".js.map");
      fs.writeFileSync(file.replace(/.[w]+$/, ".js"),
                       output.code + "n//# sourceMappingURL=" + sourceMapFile);
      fs.writeFileSync(sourceMapFile, output.map);
    });

    Note that our script will automatically add the //# sourceMappingURL comment directive so that the browser’s debugger knows where to find the source map.

    After you create the script, update your package.json:

    ...
    "bin": {
      "rpn.js": "./bin/rpn.js"
    },
    ...

    And link the package again so that the script is installed on your system:

    $ npm link .

    Seeing Results

    Here is an RPN program that we can use to test our compiler. I have saved it in examples/simple-example.rpn:

    a 8 =;
    b 3 =;
    c a b 1 - / =;
    c 1 print;

    Next, compile the script:

    $ cd examples/
    $ rpn.js simple-example.rpn

    This generates simple-example.js and simple-example.js.map. When we include the JavaScript file in a web page we should see the result of the computation printed on the page:

    Screenshot of simple-example.rpn's result

    Great success!

    However, we aren’t always so lucky, and our arithmetic might have some errors. Consider the following example, examples/with-error.rpn:

    a 9 =;
    b 3 =;
    c a b / =;
    c a b c - / =;
    c 1 print;

    We can compile this script and include the resulting JavaScript in a web page, but this time we won’t see any output on the page.

    By opening the debugger, setting the pause on exceptions option, and reloading, we can see how daunting debugging without source maps can be:

    Screenshot of enabling pause on exceptions.

    Screenshot of debugging with-error.rpn without source maps.

    The generated JavaScript is difficult to read, and unfamiliar to anyone who authored the original RPN script. By enabling source maps in the debugger, we can refresh and the exact line where the error ocurred in our original source will be highlighted:

    Screenshot of enabling source maps.


    Screenshot of debugging with-error.rpn with source maps.

    The debugging experience with source maps is orders of magnitude improved, and makes compiling languages to JavaScript a serious possibility.

    At the end of the day though, the debugging experience is only as good as the information encoded in the source maps by your compiler. It can be hard to judge the quality of your source maps simply by looking at the set of source location coordinates that they are mapping between, so Tobias Koppers created a tool to let you easily visualize your source maps.

    Here is the visualization of one of our source maps:


    Screenshot of the source map visualization tool.

    Good luck writing your own compiler that targets JavaScript!

    References

  4. Firefox Developer Tool Features for Firefox 23

    Another uplift has left the building and it’s time to take a look at what’s in Firefox Developer Tools in Firefox 23 currently Aurora, our pre-beta channel. You can download it from the Aurora Download page today. Firefox 23 is currently scheduled to hit the release channel on Tuesday August 6th, 2013.

    Episode XXIII is a barn-storming, hair-raising spectacle of incredible epicness that is sure to delight and amuse. If you want a sneak peak at features under active development, give Nightly a try.

    Network Monitor

    There’s a new tool in the toolbox: The Network Monitor. It’s a classic waterfall timeline view of network activity on a site. This data’s been available since Firefox 4 via the Web Console, albeit in a less visually pleasing way.

    Please file bugs under the Developer Tools: Netmonitor component in Bugzilla.

    Remote Style Editor

    In Firefox 23, you can now edit styles via a Remote Connection on a suitably-enabled device. This should be great help for App Developers interested in testing and debugging styles on a mobile device over the remote protocol in real time.

    As of the time of this writing, the Remote Style Editor should be compatible with Firefox for Android version 23, also scheduled for uplift to Aurora. We are working on incorporating the Style Editor Actors for the remote protocol into the Firefox OS Simulator and investigating what it will take to backport them to Firefox OS release.

    Options Panel

    We’ve added a Gear menu to the Toolbar containing an Options panel for turning tools on or off. As we add more stuff, this is going to be a popular place to manage preferences related to the Developer Tools.

    Currently, there are options to turn on the Light or Dark theme for the tools and enable Chrome Debugging.

    Initial SourceMap Support for Debugger Protocol

    The first pieces of SourceMap support for the Debugger have landed and we are now able to serve up SourceMapped JS files for your debugging pleasure. Soon to follow will be column support for breakpoints allowing you to debug minified JS with a SourceMap.

    Watch for the upcoming blog post by Nick Fitzgerald on Hacks explaining the magic.

    Variables View Everywhere

    Our Variables View is an improved Object Inspector and an integral part of our Debugger. Naturally, we wanted to put it in Everything. So now the Web Console and Scratchpad have a Variables View. Use the ESC key to close it.

    Browser Console

    If you have Chrome Debugging turned on, check out the Browser Console. It’s a replacement for the ancient Error Console and gives you a Chrome-context command line for executing JavaScript against the browser. It’s nice and should be enabled by default in Firefox 24.

    GCLI Appcache Command

    We finally have a little something for developers trying to use App Cache to store offline data. A new appcache command for the Graphical Command Line. You can read about it in Mike Ratcliffe’s The Application Cache is no longer a Douchebag.

    Web Console in Debugger Frame

    The Web Console is now fully-remoted (and has been since version 18). It now makes use of the Debugger’s current Frame if paused on a breakpoint.

    Multiple Paused Debuggers

    You can now debug multiple tabs at the same time using the Script Debugger. Previously, when attempting to use the debugger on two separate tabs, you’d be given a notification to resume the debugger in the other tab. Now you can debug as many tabs as you like.

    There is one caveat to this awesome power, however. Due to the nested event loops each Debugger creates, you have to resume each tab in the order in which they were paused. Debug carefully and always carry a big stack.

    You can see a comprehensive list of bugfixes in table form in Firefox 23 Developer Tools Fixes.

  5. HiDPI support, HTML5 notifications, Parallel JS, asm.js and more – Firefox Development Highlights

    Time for another look at the latest developments with Firefox. This is part of our Bleeding Edge and Firefox Development Highlights series, and most examples only work in Firefox Nightly (and could be subject to change).

    HiDPI support

    We’re happy to say that ico/icns with multiple images are now supported: the highest resolution icon is now used on HiDPI/Retina displays.

    Favicon implementation is described in bug 828508 and ico/icns is described in bug 419588.

    Performance improvements/Snappy:

    Numerous performance improvements have been made, such as faster startup, better scrolling on touchpads and smoother animations.

    The most important improvement, however, is probably multithreaded image decoder. The result should be faster page loads and tab switching. All the nitty-gritty detalis are described in bug 716140.

    HTML5

    When it comes to the world of HTML5 & friends, we have some good additional support:

    <input type=”range”>

    We now support the <input type="range"> element in forms. To style it, you can use the ::-moz-range-progress:

    ::-moz-range-progress {
        background: #f00;
    }
     
    <input type="range">

    You can see this <input type=”range”> demo in action on jsFiddle.

    HTML5 notifications

    HTML5 notifications have now been implemented. Basically, you ask for permission and then you can create a notification:

    function authorizeNotification() {
        Notification.requestPermission(function(perm) {
            alert(perm);
        });
    }
     
    function showNotification() {
        var notification = new Notification("This is a title", {
            dir: "auto",
            lang: "",
            body: "This is a notification body",
            tag: "sometag",
        });
    }

    See the HTML5 notification demo in action on jsFiddle.

    WebAudio API activated by default

    WebAudio API has been activated by default in Firefox Nightly. Testers welcome, though there are still work to be done before it can be released.

    JavaScript

    Parallel JS

    The first version of Parallel JS has landed for Firefox. A lot more details in the Parallel JS Lands article.

    asm.js

    We’re happy to say that asm.js is now in Firefox, scheduled to be released in Firefox 22! Luke Wagner has written more about it in asm.js in Firefox Nightly.

    ES6 Arrow function syntax

    We now support the ES6 Arrow function syntax

    let square = x => x*x;
    console.log(square(3));

    CSS

    @supports activated by default

    We plan on releasing this with Firefox 22. More about @supports on MDN.

    min-width and min-height ‘auto’ keyword

    min-width and min-height 'auto' keyword is no more supported. It has been removed from CSS3 Flexbox. More about that in bug 848539.

    CSS Flexbox has been re-enabled

    Happy to let you know that CSS Flexbox has been re-enabled by default in Firefox 22, which is currently in Firefox Aurora!

  6. Developer Tools Update – Firefox 22

    This is the first in a series of posts published on or about the time a new Firefox version graduates from ‘Nightly’ status and becomes Firefox Aurora. We think that is the absolute best time to let you know about all the cool new developer-related features that have landed in the last 6 weeks, and we encourage you to check out Firefox Aurora if you haven’t already.

    What’s that font?

    First up, a handy new pane has been added to the Inspector that lets you inspect whatever font rules are applied to the selected html node, or optionally you can view all fonts being used on the page in a single view:

    Web_fonts_example

    We see this as being particularly helpful for fine-tuning cross-platform font differences, or testing how web fonts are working in your app.

    Let’s re-paint

    The developer toolbox also has a new mode that visualizes what parts of the page are being re-painted by Firefox using a colorful ‘flashing’ effect. I recorded a quick 1-minute screencast to give you an idea of how it works:

    In modern web apps we tend to rely heavily on JS libraries and CSS animations to bring user experiences alive, but in order to get the experience we need it’s important to understand how hard the browser is working to display the page. Visual Paint mode seeks to give insight into all of this.

    Toolbox on the side

    Wide-screen laptop and desktop LCD monitors are now the norm so we added a nice way to switch the Toolbox location to the right side of the browser window in addition to the bottom of the window or as a separate window:

    dock-to-side
  7. Ambient Light Events and JavaScript detection

    I think that one of the most interesting things with all WebAPIs we’re working on, is to interact directly with the hardware through JavaScript, but also, as an extension to that, with the environment around us. Enter Ambient Light Events.

    The idea with an API for ambient light is to be able to detect the light level around the device – especially since there’s a vast difference between being outside in sunlight and sitting in a dim living room – and adapt the user experience based on that.

    One use case could be to change the CSS file/values for the page, offering a nicer reading experience under low light conditions, reducing the strong white of a background, and then something with more/better contrast for bright ambient light. Another could be to play certain music depending on the light available.

    Accessing device light

    Working with ambient light is quite simple. What you need to do is apply a listener for a devicelight event, and then read out the brightness value.

    It comes returned in the lux unity. The lux value ranges between low and high values, but a good point of reference is that dim values are under 30 lux, whereas really bright ones are 10,000 and over.

    window.addEventListener("devicelight", function (event) {
        // Read out the lux value
        var lux = event.value;
        console.log(lux);});

    Web browser support

    Ambient Light Events are currently supported in Firefox on Android, meaning both mobile phones and tablets, and it’s also supported in Firefox OS. On Android devices (the ones I’ve tested), the sensor is located just right to the camera facing the user.

    It is also a W3C Working Draft, following the type of other similar events, such as devicemotion, so we hope to see more implementations of this soon!

    Demo

    Dmitry Dragilev and Tim Wright recently wrote a blog post about the Ambient Light API, with this nice demo video:

    You can also access the demo example directly, and if you test in low light conditions, you’ll get a little music. Remember to try it out on a supported device/web browser.

  8. Firefox Developer Tools work week wrap-up

    Last week in Sunnyvale we had the first Developer Tools work week to include the recently-integrated Jetpack team ( for a slightly different take on the week, see Paul’s post. ). And what a week! I was a bit shocked by how many things I thought were just interesting ideas suddenly became real things that actually worked. By Friday morning we had some amazing demos from the team, which I will try to group together according to theme:

    Remote everything, everywhere.

    Within the next 3 months we will land remote protocol support for all of the development tools we ship. The remote protocol is a network client/server protocol that exposes the developer tools to each other external tools like editors as well as Firefox on Android and Firefox OS. We had some awesome demos that leverage or extend these capabilities:

    • Based on Heather Arthur’s work on implementing remote style editing, Paul Rouget amazed us and soon many others with remote CSS editing from popular editor Sublime Text 2: (Tweet, Youtube, Github).
    • Joe Walker showed off how to run gcli commands remotely between different instances of Firefox Desktop.
    • Jim Blandy walked us through some important platform fixes that will enable content process debugging on Firefox OS. This will allow us to support remote on-device debugging of B2G apps.

    Revolutionary Dev Tools hacks

    Many team members got a ton of work done on their existing projects and showed us some great enhancements by the end of the week:

    • Mihai Sucan showed off progress on the Global Console, which now understands all network requests and also supports stdin/stdout and some handy timing utilities.
    • Anton Kovalyov showed off an initial integration of Codemirror as the source editor for the devtools, replacing the current Orion editor.
    • Nick Fitzgerald got sourcemaps working with the debugger and gave us a demo of Coffeescript debugging.
    • Joe Walker re-factored gcli commands to de-couple processing from presentation, making it much easier to implement multiple commands that use a common data formatter.
    • Last but not least, Victor Porov walked us through a fully-operational Network Panel that is nearly ready to land!
    • Stephen Shorlander showed off some great first steps on defining what in-browser web app development might look like.

    Developer tools + Jetpack == Super Powers!

    On Tuesday Paul Rouget walked us through the fledgling developer tools API and challenged the Jetpack team to see how working with the developers could be made simpler. By Friday Irakli answered the challenge by showing us a Jetpack add-on called ‘Add-on Pad’ for live-coding SDK-based add-ons.

    Dave Camp had a slightly different take on Jetpack’s possibilities and by the end of the week was able to show off a version of the Developer Tools code-base that could be dynamically re-loaded from disk using Jetpack’s CommonJS loader, without the need to re-build or even restart Firefox.

    Not to be outdone, Dave Townsend made some tweaks to tilt mode to expose it to add-ons and even scratchpad hacks to change how tilt visualizes a page based on arbitrary code that could be injected either via an add-on or from scratchpad.

    Paul also released a new version of his excellent Firefox Terminal add-on recently which you should go install it immediately! Right now! I’ll still be here when you get back.

    Add-on developer love

    The developer tools team has been focused like a laser on improving life for web developers, but Firefox itself is created and extended with web technologies like JS and CSS. At this first Devtools work week that included the Jetpack team we saw some really promising work:

    • Eddy Bruel tackled several bugs I don’t completely understand and by the end of the week showed us debugging for almost all browser chrome and add-on Javascript code. There are still some known limitations to work through ( not all add-ons or content scripts can be debugged currently ) but the Browser is already very useful to developers as of today’s Nightly build.
    • Mihai Sucan and Alexandre Poirot made changes to both the SDK and the Global Console that will pipe any calls to console.log in Jetpack code to the Global Console, greatly improving ‘printf’-style debugging for add-on developers.

    Some of these hacks landed last week during the work week, many will be landing over the next couple weeks. If you’d like to get involved in driving these features home, find us in #devtools and #jetpack on irc.mozilla.org or the Developer Tools project mailing list at mozilla.dev.developer-tools.

  9. Font Inspector and <time> and <data> elements – Firefox Development Highlights

    Time for another look at the latest developments with Firefox. This is part of our Bleeding Edge and Firefox Development Highlights series, and most examples only work in Firefox Nightly (and could be subject to change).

    Font Inspector

    A Font Inspector is now available in the Firefox DevTools.

    image

    In the Firefox Inspector, a “Fonts” panel is now available. It exposes different information about the @font-faces used in the page:

    • Font name and font family
    • Its location (system vs. remote, and URL)
    • A preview (you can change it)
    • @font-face code

    HTML5 and

    We have implemented support for two new elements:

    <time> element

    The HTML time element (

    Example:

    <p>The concert took place on <time datetime="2001-05-15 19:00">May 15</time>.</p>

    More information can be found in the MDN documentation for the <time> element, and in the W3C specification.

    <data> element

    The data element represents its contents, along with a machine-readable form of those contents in the value attribute. The value attribute must be present and its value must be a representation of the element’s contents in a machine-readable format.

    The <data> element adds a new attribute, value, which contains a string representation of the data. In script we can use the .value property to get the reflected value:

    Example:

    <data id="user" value="humphd">David Humphrey</data>
    document.getElementById("user").value; // "humphd"

    It’s available in the WHATWG specification, and David Humphrey’s wrote more about it in HTML5 time and data elements in Firefox.

  10. WebRTC enabled, H.264/MP3 support in Win 7 on by default, Metro UI for Windows 8 + more – Firefox Development Highlights

    Time again for looking at the latest progress with Firefox. These posts are part of our Bleeding Edge and Firefox Development Highlights series – take note that most examples only work in Firefox Nightly (and could be subject to change).

    WebRTC enabled by default

    Previously, you needed to go to about:config in Firefox and set the media.peerconnection.enabled option to true, but now it’s enabled by default. This is a huge step forward, to be able to run WebRTC directly in a web browser without it needing any special settings or configuration.

    For more details behind this decision, please read Pref on WebRTC by default.

    Want to get started with WebRTC? Then we recommend our article Cross-browser camera capture with getUserMedia/WebRTC.

    Metro UI

    The new Firefox User Interface for Windows 8 has landed (if you had Firefox Nightly as your default browser, reset that permission to see the new UI).

    There are more screenshots available too.

    H.264 & MP3 support enabled by default in Windows 7

    We talked about H.264 & MP3 support before, and now that support is activated by default.

    We are still working on supporting Mac OS X and Linux.

    WebAudio API progress

    We are working on implementing the WebAudio API, and the first parts of support has just started appearing.

    It’s available in about:config in the media.webaudio.enabled preference – set it to true to enable it and be able to access things such as AudioContext.decodeAudioData.

    Crypto API: window.crypto.getRandomValues

    If you provide an integer-based TypedArray (i.e. Int8Array, Uint8Array, Int16Array, Uint16Array, Int32Array, or Uint32Array), window.crypto.getRandomValues is going fill the array with cryptographically random numbers:

    /* assuming that window.crypto.getRandomValues is available */
     
    var array = new Uint32Array(10);
    window.crypto.getRandomValues(array);
     
    console.log("Your lucky numbers:");
    for (var i = 0; i < array.length; i++) {
        console.log(array[i]);
    }

    canvas: ctx.isPointInStroke

    This has been uplifted to Firefox 19 Beta.

    From the WHATWG mailing list:

    “We have recently implemented isPointInStroke(x,y) in Firefox (https://bugzilla.mozilla.org/show_bug.cgi?id=803124). This is a parallel to isPointInPath(x,y) and returns true if the point is inside the area contained by the stroking of a path.”

    JavaScript: Math.imul

    Math.imul allows for fast 32-bit integer multiplication with C-like semantics. This feature is useful for projects like Emscripten.

    Polyfill:

    function imul(a, b) {
        var ah  = (a >>> 16) & 0xffff;
        var al = a & 0xffff;
        var bh  = (b >>> 16) & 0xffff;
        var bl = b & 0xffff;
        // the shift by 0 fixes the sign on the high part
        return (al * bl) + (((ah * bl + al * bh) << 16) >>> 0);
    }