1. HTML5 context menus in Firefox (Screencast and Code)

    You may not know it, but the HTML5 specifications go beyond what we put in the pages and also define how parts of the browser should become available to developers with HTML, CSS and JavaScript. One of these parts of the specs are context menus, or “right click menus”. Using HTML5 and a menu element you can add new options to these without having to write a browser add-on. In Firefox 8 (the current one) we have support for those. See the following screencast for a context menu demo.

    The image example is pretty simple and was actually written by Paul Rouget as a demo in the original Firefox bug request. The main core is the HTML of it:

    <section id="noninteractive" contextmenu="imagemenu">
     
      <img src="html5.png" alt="HTML5" id="menudemo">
     
        <menu type="context" id="imagemenu">
          <menuitem label="rotate" onclick="rotate()"
                    icon="arrow_rotate_clockwise.png">
          </menuitem>
          <menuitem label="resize" onclick="resize()"
                    icon="image-resize.png">
          </menuitem>
          <menu label="share">
            <menuitem label="twitter" onclick="alert('not yet')"></menuitem>
            <menuitem label="facebook" onclick="alert('not yet')"></menuitem>
          </menu>
        </menu>
     
    </section>

    As you can see you link the menu element to an element via its ID. The contextmenu attribute then points to this one. Each menu can have several menuitems. Each of those gets a textual label and a possible icon. You can also nest menu elements to create multiple layer menus. Here, we add inline onclick handlers to point to different JavaScript functions to call when the menu item gets activated. The resulting context menu looks like this:

    image with a context menu

    The functionality is simple, all the rotate() and resize() functions do is add class names to the image using querySelector and classList:

    function rotate() {
      document.querySelector('#menudemo').classList.toggle('rotate'); 
    }
    function resize() {   
      document.querySelector('#menudemo').classList.toggle('resize'); 
    }

    The real effect is in CSS transforms and transitions. As the image has an ID of menudemo here is what is needed in CSS to rotate and resize:

    #menudemo { 
      -moz-transition: 0.2s; 
      width:200px;
    }
    #menudemo.rotate { 
      -moz-transform: rotate(90deg); 
    }
    #menudemo.resize { 
      -moz-transform: scale(0.7); 
    }
    #menudemo.resize.rotate { 
      -moz-transform: scale(0.7) rotate(90deg); 
    }

    Notice that in a real product we should of course add the other browser prefixes and go prefix-less but as the functionality now only works in Firefox, this is enough for this demo.

    Detecting support and visual hinting

    Now, as this is extending the normal user offerings in the browser we need to make it obvious that there is a right-click menu available. In CSS3, there is a context-menu cursor available to us. When context menus are available, this should be shown:

    .contextmenu #menudemo, .contextmenu .demo {
      cursor: context-menu;
    }

    We test the browser for support by checking for contextmenu on the body element and for HTMLMenuItemElement in the window (this has been added as a pull request to Modernizr, too).

    if ('contextMenu' in document.body && 'HTMLMenuItemElement' in window) {
      document.documentElement.classList.add('contextmenu');
    } else {
      return;
    }

    Wouldn’t HTMLMenuItemElement be enough? Yes, but a real context menu should only offer functionality when it is sensible, and that is where contextMenu comes in.

    Turning menuitems on and off depending on functionality

    As a slightly more complex example, let’s add a “count words” functionality to the document. For this, we generate a counter element that will become a tooltip when the words were counted:

    var counter = document.createElement('span');
    counter.id = 'counter';
    counter.className = 'hide';
    document.body.appendChild(counter);
     
    counter.addEventListener('click', function(ev){
      this.className = 'hide';
    },false);

    This one is hidden by default and becomes visible when the hide class is removed. To make it smooth, we use a transition:

    #counter{
      position: absolute;
      background: rgba(0,0,0,0.7);
      padding:.5em 1em;
      color: #fff;
      font-weight:bold;
      border-radius: 5px;
      -moz-transition: opacity 0.4s;
    }
    #counter.hide{
      opacity: 0;
    }

    We start with two sections with context menus:

    <section id="noninteractive" contextmenu="countmenu">
      <menu type="context" id="countmenu">
          <menuitem class="wordcount" label="count words"></menuitem>
      </menu>
    </section>
     
    <section id="interactive" contextmenu="countmenuinteractive">
      <menu type="context" id="countmenuinteractive">
          <menuitem class="wordcount" label="count words"></menuitem>
      </menu>
    </section>

    We then loop through all the menuitems with the class wordcount and apply the functionality.

    var wordcountmenus = document.querySelectorAll('.wordcount'),
        i = wordcountmenus.length;
     
    while (i--) {
      wordcountmenus[i].addEventListener('click', function(ev){
        // add functionality 
      }, false);
    }

    We need to find out what has been selected in the page. We do this by using getSelection() and splitting its string version at whitespace. We then show the counter by removing the hide class name.

    var wordcountmenus = document.querySelectorAll('.wordcount'),
        i = wordcountmenus.length;
     
    while (i--) {
      wordcountmenus[i].addEventListener('click', function(ev){
        var text = document.getSelection(),
            count = text.toString().split(/\s/).length;
        counter.innerHTML = count + ' words';
        counter.className = '';
      }, false);
    }

    You can see this in action in the second context menu demo. Now, the issue with this (as explained in the screencast) is that it always counts the words, regardless of the user having selected some text. What we want is the menu only to be active when there is text selected.

    context menu item available or not available depending on selection

    So in order to make our menu only become available when it makes sense we check if there is a selection in the document. Every context menu fires an event called contextmenu when it opens. So all we need to do is to subscribe to this event.

    When something is selected in the document document.getSelection().isCollapsed is true. Otherwise it is false, so all we need to do is to enable or disable the menu item accordingly:

    document.querySelector('#interactive').addEventListener(
      'contextmenu', function(ev) {
        this.querySelector('.wordcount').disabled =
        document.getSelection().isCollapsed;  
      },
    false);

    The last thing to solve is the position of the mouse to position the counter element. As the menu selection event doesn’t give us the mouse position we need to add a contextmenu handler to the whole document that positions the counter invisibly behind the menu when it is opened:

    document.body.addEventListener(
      'contextmenu', function(ev) {
        counter.style.left = ev.pageX + 'px';
        counter.style.top = ev.pageY + 'px';
        counter.className = 'hide';
      }, 
    false);

    Further reading and resources

  2. insertAdjacentHTML() Enables Faster HTML Snippet Injection

    The following is a guest post by Henri Sivonen:

    In Firefox 8, we’ve added support for insertAdjacentHTML(). It’s an ancient feature of Internet Explorer that has recently been formalized in HTML5 and then spun out into the DOM Parsing specification. The bad news is that Firefox is the last major browser to implement this feature. The good news is that since other major browsers implement it already, you can start using it unconditionally as soon as the Firefox 8 update has been rolled out to users.

    Basic Usage

    insertAdjacentHTML(position, markup) is a method on HTMLElement DOM nodes. It takes two string arguments. The first argument is one of "beforebegin", "afterbegin", "beforeend", or "afterend" and gives the insertion point relative to the node that insertAdjacentHTML() is invoked on. The second argument is a string containing HTML markup that gets parsed as an HTML fragment (similar to a string assigned to innerHTML) and inserted to the position given by the first argument.

    If the node that insertAdjacentHTML() is invoked on is a p element
    with the text content “foo”, the insertion points would be where the comments are in the following snippet:

    <!-- beforebegin --><p><!-- afterbegin -->foo<!--
    beforeend --></p><!-- afterend -->

    The "beforebegin" and "afterend" positions work only if
    the node is in a tree and has an element parent.

    For example, consider the following code:

    <div id=container><p id=para>foo</p></div>
    <script>
      document.getElementById("para").insertAdjacentHTML("beforeend", "<span>bar</span>");
      console.log(document.getElementById("container").innerHTML);
    </script>

    This code produces this log output:

    <p id="para">foo<span>bar</span></p>

    Well, that does not look particularly special. In fact, it looks like something that could have been done using plain old innerHTML. So why bother with insertAdjacentHTML() when element.innerHTML += "markup"; already works?

    There are two reasons.

    • insertAdjacentHTML() doesn’t corrupt what’s already in the DOM.
    • insertAdjacentHTML() is faster.

    Avoiding DOM corruption

    Let’s consider the DOM corruption issue first. When you do element.innerHTML += "markup";, the browser does the following:

    1. It gets the value of innerHTML by serializing the descendants of element.
    2. It appends the right hand side of += to the string.
    3. It removes the children of element.
    4. It parses the new string that contains the serialization of the old descendants followed by some new markup.

    The old descendants might have been script-inserted to form a subtree that doesn’t round-trip when serialized as HTML and reparsed. In that case, after the operation, the tree would have a different shape even for the “old” parts. (For example, if element had a p child which in turn had a div child, the subtree wouldn’t round-trip.) Furthermore, even if serializing and reparsing resulted in a same-looking tree, the nodes created by the parser would be different nodes than the nodes that were children of element at first. Thus, if other parts of the JavaScript program were holding references to descendants of element, after element.innerHTML += "markup"; had been executed, those references would point to detached nodes and element would have new similar but different descendants.

    When additional content is inserted using insertAdjacentHTML(), the existing nodes stay in place.

    Better performance

    Serializing and reparsing is also what leads to performance problems with the element.innerHTML += "markup"; pattern. Each time some more content is appended, all the existing content in element gets serialized and reparsed. This means that appending gets slower and slower, because each time there more and more previous content to serialize and reparse.

    Using insertAdjacentHTML() can make a big difference. For testing purposes, I started with an empty div and ran a loop that tried to append as many tweets as possible to the div in five seconds. A tweet is actually rather large when you count all the mark-up that implements @mention linkification, the name of the tweeter, retweet and favoriting UI, etc. It weighs about 1600 characters of HTML source—most of it mark-up.

    On the computer that I used for testing, the innerHTML way of appending managed to append only slightly over 200 tweets in five full seconds. In contrast, the insertAdjacentHTML("beforeend", ...) way of appending managed to append almost 30,000 tweets in 5 seconds. (Yes, that’s hundreds versus tens of thousands.) Obviously, real Web apps should never block the event loop for five seconds—this is just for benchmark purposes. However, this illustrates how the innerHTML way of appending becomes notably slower as more and more content accumulates to be serialized and reparsed each time.

    At this point, some readers might wonder if insertAdjacentHTML() offers any benefit over createContextualFragment(). After all, conceptually insertAdjacentHTML() creates a fragment and inserts it.

    Using createContextualFragment(), my test manages only slightly over 25,000 tweets in five seconds, while using insertAdjacentHTML() manages slightly under 30,000. This is because Gecko accelerates insertAdjacentHTML() when the insertion point has no next sibling (only for HTML though—not for XML so far). The "beforeend" insertion point never has a next sibling and is always accelerated (for HTML). The "beforebegin" insertion point always has a next sibling (the node that insertAdjacentHTML() was invoked on) and is never accelerated. For "afterbegin" and "afterend", whether the operation is accelerated depends on the situation.

    In conclusion, you can make your Web app perform better by using element.insertAdjacentHTML("beforeend", "markup"); where you currently use element.innerHTML += "markup";.

  3. Using CORS to load WebGL textures from cross-domain images

    In Firefox, as well as in Chrome, it is now possible to load cross-domain images into WebGL textures, if they have been approved by CORS.

    Most prominently, this feature allows for impressive 3D mapping applications such as Google MapsGL and Nokia Maps 3D.

    What happened

    Earlier this year, the Editor’s Draft WebGL specification got updated in response to a security concern. The additions were:

    1. A mandatory clause disallowing usage of cross-domain elements as WebGL textures in the general case.
    2. A non-normative clause specifically allowing cross-domain elements that have CORS approval. For that occasion, the HTML specification on the <img> element got updated to add a new crossorigin attribute.

    The first got implemented in Firefox 5, the second is now in Firefox 8.

    How to use this feature

    There are two CORS modes: “anonymous” and “use-credentials”. We’ll focus on “anonymous” as it’s the common case. A great example of images served with anonymous CORS is Google Maps imagery, such as:

    http://khm0.googleapis.com/kh?v=95&x=0&y=0&z=0

    In order to load it with CORS as a WebGL texture, we set the crossOrigin attribute on it:

    var earthImage = new Image();
    earthImage.crossOrigin = "anonymous";

    Now we load it as usual:

        earthImage.onload = function() {
          // whatever you usually to do load WebGL textures
        };
        earthImage.src = "http://khm0.googleapis.com/kh?v=95&x=0&y=0&z=0";

    That’s it! Aside from setting the crossOrigin attribute, we didn’t have to do anything. Here is the full self-contained example.

    The HTTP headers

    If we study the HTTP headers for this image (using, for example, Firefox’s Web Console), we find that the Request Headers contain

    Origin: null

    which is the effect of having set this crossOrigin attribute on the img element. And the Response Headers contain

    Access-Control-Allow-Origin: null

    which is the effect of the server supporting CORS for this file.

    Doing this in HTML

    Of course, one could also set this attribute in HTML, in which case it’s case-insensitive:

    <img src="http://khm0.googleapis.com/kh?v=95&x=0&y=0&z=0" crossorigin="anonymous">

    And since “anonymous” is both the missing-value-default and the invalid-value-default for the crossorigin attribute, we can pass any invalid value for it, or even just omit its value:

    <img src="http://khm0.googleapis.com/kh?v=95&x=0&y=0&z=0" crossorigin>

    Coming soon: CORS approval for Canvas 2D drawImage

    What if you first draw a CORS-approved cross-domain image onto a 2D
    canvas, and then use that canvas as the source of a WebGL texture? The
    good news is that this will work in Firefox 9, which is hitting the Beta
    channel soon. This fix means that demos like this will work really
    nicely in Firefox 9.